Answer to Question #171141 in C++ for Myles Clement

Question #171141

Create a program with this statement to declare a array of integers.  int myarray[]={4,77,6,22,3,98};


In the same program create a linked list of integers and in a loop, cycle through the array and store the five values in the linked list.


1
Expert's answer
2021-03-12T14:59:02-0500
#include <iostream>
using namespace std;

// Representation of a node
struct Node {
    int data;
    Node* next;
};

// Function to insert node
void insert(Node** root, int item)
{
    Node* temp = new Node;
    Node* ptr;
    temp->data = item;
    temp->next = NULL;

    if (*root == NULL)
        *root = temp;
    else {
        ptr = *root;
        while (ptr->next != NULL)
            ptr = ptr->next;
        ptr->next = temp;
    }
}

void display(Node* root)
{
    while (root != NULL) {
        cout << root->data << " ";
        root = root->next;
    }
}

Node *arrayToList(int myarray[], int n)
{
    Node *root = NULL;
    for (int i = 0; i < n; i++)
        insert(&root, myarray[i]);
return root;
}

// Driver code
int main()
{
    int myarray[]={4,77,6,22,3,98};

    int n = sizeof(myarray)/sizeof(myarray[0]);
    for(int i=0;i<n;i++){
        printf("%d,",myarray[i]);
    }
    Node* root = arrayToList(myarray, n);

    cout<<"\n The required linked list"<<endl;
    display(root);
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS