-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsert_Node_at_specific_position_of_linked_list.c
More file actions
102 lines (90 loc) · 2.36 KB
/
Copy pathInsert_Node_at_specific_position_of_linked_list.c
File metadata and controls
102 lines (90 loc) · 2.36 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// Insert Node at specific position in Linked List
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *link;
};
struct node *head = NULL, *temp = NULL, *newnode = NULL;
int count = 0;
void create_linked_list();
void display_list();
void insert_node_at_specific_position();
int main()
{
create_linked_list();
display_list();
printf("\nIn Linked List %d nodes are present\n", count); /*count variable is declared globally already and count variable is used for get the length of linked list, and in display_list() count variable is used for get the length of linked list, and in main() I print this.*/
insert_node_at_specific_position();
display_list();
return 0;
}
void create_linked_list()
{
int choice = 1;
while(choice == 1)
{
newnode = (struct node *)malloc(sizeof(struct node));
if(newnode==NULL)
{
printf("Memory Not allocate.");
}
else
{
printf("Enter Data\n");
scanf("%d", &newnode->data);
newnode->link = NULL;
if (head == NULL)
head = temp = newnode;
else
{
temp->link = newnode;
temp = newnode;
}
printf("Do You add another node in the list? if yes, press 1 else 0\n");
scanf("%d", &choice);
}
}
}
void display_list()
{
temp = head;
printf("\nAfter insert data in Linked List the data are\n");
while (temp != NULL)
{
printf("%d ", temp->data);
count++;
temp = temp->link;
}
}
void insert_node_at_specific_position()
{
int pos, i = 1;
printf("\nEnter the Position in which you insert a node\n");
scanf("%d", &pos);
if(pos<=1 || pos>=count)
{
printf("Invalid position.\n");
}
else
{
temp = head;
newnode = (struct node *)malloc(sizeof(struct node));
if(newnode == NULL)
printf("Memory Not allocate for new node.");
else
{
printf("Enter data of newly created node\n");
scanf("%d", &newnode->data);
newnode->link = NULL;
while (i < pos - 1)
{
temp = temp->link;
i++;
}
newnode->link = temp->link;
temp->link = newnode;
}
}
}