Insertion In Linked List
Goal: Insert a given element at a given location in linked list.
Method-Used: By changing the address specified by next pointer(link) in a node.
Steps:
1. Track the location where you want to insert a node.
2.Store the address of its prevoius and next node.
3.Now create a new node and assign its address to previous node's link part.
4.Assign address of next node to new node's link part.
Example:
Suppose we want to insert a new node N between A and B in given Link list.
Before Insertion next pointer of node A points to node B but After insertion next-pointer of node A will point to Node N and next-pointer of N will point to node B.
Program:
#include<iostream>
#include<conio.h>
using namespace std;
struct node {
int info;
node *next;
};
node *head1;
node *create()
{
int n,i,data,;
node *p1,*temp1;
head1=NULL;
temp1=NULL;
cout<<"\n\tHow many Elements you want to enter:\n";
cout<<"\t";
cin>>n;
cout<<"\n\t Enter Elemnts:\n";
for(i=0;i<n;i++)
{
cout<<"\t";
cin>>data;
if(head1==NULL)
{
p1=new node;
p1->info=data;
p1->next=NULL;
head1=p1;
temp1=p1;
}
else
{
p1=new node;
p1->info=data;
p1->next=NULL;
temp1->next=p1;
temp1=p1;
}
}
p1=head1;
return p1;
}
void display(node *p2)
{
cout<<"\t";
cout<<"Displaying:--\n";
while(p2)
{
cout<<"\t";
cout<<p2->info<<"\t";
p2=p2->next;
}
}
node * insert(node *p2)
{
int m,k,count=0;
node *temp,*cash,;
temp=head1;
cash=NULL;
p2=head1;
cout<<"\n\tEnter element to be inserted-\n";
cout<<"\t";
cin>>m;
cout<<"\t";
cout<<"Enter the position of new element..\n";
cout<<"\t";
cin>>k;
while(p2)
{
count++;
if(count==k)
{
cash=p2;
p2=new node;
p2->info=m;
p2->next=cash;
if(k==1)
head1=p2;
else
temp->next=p2;
p2=p2->next;
}
else
{
temp=p2;
p2=p2->next;
}
}
p2=head1;
return p2;
}
int main()
{
node *p1,*head,*temp;
head=NULL;
temp=NULL;
p1=create();
display(p1);
p1=insert(p1);
display(p1);
getch();
}
0 comments:
Post a Comment