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.
#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;
}
Comments
Leave a comment