-
Notifications
You must be signed in to change notification settings - Fork 0
/
insert_a_node.cpp
61 lines (61 loc) · 1.16 KB
/
insert_a_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
#include <stdio.h>
struct node{
int data;
struct node* next;
};
int main()
{
struct node *p,*q,*t,*r;
int x;
p = new node;
printf("Enter the first value: ");
scanf("%d",&p->data);
printf("Enter the next value: ");
scanf("%d",&x);
q = p;
while(x)
{
t = new node;
t->data = x;
q->next = t;
q = q->next;
printf("Enter the next value: ");
scanf("%d",&x);
}
q->next = NULL;
q = p;
printf("First List is : ");
while(q)
{
printf("%d ",q->data);
q=q->next;
}
printf("\n");
int new_val,pos;
printf("Where You Want To Insert A Node : ");
scanf("%d %d",&new_val,&pos);
r = new node;
r->data = new_val;
r->next = NULL;
q = p;
if(pos == 1){
r->next = p;
p = r;
}
else{
for(int i = 1;i<=pos-2;i++){
q = q->next;
}
r->next = q->next;
q->next = r;
}
q = p;
printf("New List is : ");
while(q)
{
printf("%d ",q->data);
q=q->next;
}
printf("\n");
return 0;
}