-
Notifications
You must be signed in to change notification settings - Fork 195
/
Copy pathinsert_a_node_at_end_in_Linked_List.cpp
80 lines (61 loc) · 1.29 KB
/
insert_a_node_at_end_in_Linked_List.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
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node;
node* insert_node_at_end(int node_value , node* start)
{
node *new_node , *p;
new_node = (node*)malloc(sizeof(node));
new_node->data = node_value;
new_node->next = NULL;
p = start;
while(p->next !=NULL)
{
p = p->next;
}
p->next = new_node;
return start;
}
int main()
{
int a , i = 1 , n ,r , node_data , position , node_value; // i = 0 is also ok....
node *p,*q,*start;
printf("Enter the number of nodes");
scanf("%d",&n);
printf("Enter node %d \n",i); // you can also start with i = 0
p = (node*)malloc(sizeof(node));
scanf("%d",&a);
p->data = a;
p->next = NULL;
start = p;
for(i=2;i<=n;i++) //if i=0 , then for ( i = 1; i < n; i++ )
{
printf("Enter node %d \n",i);
q = (node*)malloc(sizeof(node));
scanf("%d",&a);
q->data = a;
q->next = NULL;
p->next = q;
p = p->next;
}
p = start;
while(p!=NULL)
{
printf("\t %d", p->data);
p = p->next;
}
printf("\nEnter the value of the node which you want to insert at end");
scanf("%d",&node_value);
start = insert_node_at_end(node_value , start);
printf("\n");
p = start;
while(p!=NULL)
{
printf("\t %d",p->data);
p = p->next;
}
return 0;
}