forked from xanxit/CPP-DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
inserting a node after a specific node.cpp
85 lines (81 loc) · 1.16 KB
/
inserting a node after a specific node.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include<iostream>
using namespace std;
class Node
{
public:
int data;
Node*next;
};
Node*first=NULL;
void insert(Node*p,int pos,int val)
{ int i=0;
Node*t=NULL;
t=new Node;
if(pos==0)
{
t->data=val;
t->next=first;
first=t;
}
else
{
p=first;
while(i<pos-1)
{
p=p->next;
i++;
}
if(p!=NULL)
{
t->data=val;
t->next=p->next;
p->next=t;
}
}
}
void display(Node*p)
{
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
count++;
}
}
void afinsert(Node*p,int z,int pos)
{
Node*temp=NULL;
temp=p;
Node*newnode=NULL;
newnode=new Node;
int i=1;
while(i<pos)
{
temp=temp->next;
i++;
}
newnode->data=z;
newnode->next=temp->next;
temp->next=newnode;
}
}
int main()
{
int i,x,n;
cout<<"Enter the number of Nodes: ";
cin>>n;
for(i=0;i<n;i++)
{
cout<<"Enter data in the "<<i+1<<" node:";
cin>>x;
insert(first,i,x);
}
cout<<"\nEnter the position after which you want the new node to get inserted : ";
int c,p;
cin>>c;
cout<<"\nEnter the Value to be added : ";
cin>>p;
afinsert(first,p,c);
display(first);
return 0;
}