

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


#include #include #include struct node { int data; node *next; }; void main() { node *head, *newnode, temp; int n, i; clrscr(); / Creating given linked list: 10 -> 20 -> 30 -> NULL */ head = (node *)malloc(sizeof(node)); head->data = 10; head->next = NULL; temp = head; temp->next = (node *)malloc(sizeof(node)); temp = temp->next; temp->data = 20; temp->next = NULL; temp->next = (node )malloc(sizeof(node)); temp = temp->next; temp->data = 30; temp->next = NULL; cout << "Given Linked List: "; temp = head; while(temp != NULL) { cout << temp->data << " -> "; temp = temp->next; } cout << "NULL"; / Insert nodes at beginning */ cout << "\n\nHow many nodes do you want to insert at beginning? "; cin >> n;
for(i = 1; i <= n; i++) { newnode = (node )malloc(sizeof(node)); cout << "Enter data for new node " << i << ": "; cin >> newnode->data; newnode->next = head; head = newnode; } / Display final linked list */ cout << "\nLinked List after insertion: "; temp = head; while(temp != NULL) { cout << temp->data << " -> "; temp = temp->next; } cout << "NULL"; getch(); } Output: Given Linked List: 10 -> 20 -> 30 -> NULL How many nodes do you want to insert at beginning= Enter data for new node 1: 5 Enter data for new node 2: 7 Linked List after insertion: 7 -> 5 -> 10 -> 20 -> 30 -> NULL