Docsity

Data structure program for insertion of node, Schemes and Mind Maps of Data Structures and Algorithms

Toggle sidebar
bg1
Program to insert a node at the beginning od the linklist
#include <iostream.h>
#include <conio.h>
#include <stdlib.h>
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;
pf2

Partial preview of the text

Download Data structure program for insertion of node and more Schemes and Mind Maps Data Structures and Algorithms in PDF only on Docsity!

Program to insert a node at the beginning od the linklist

#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