-
Notifications
You must be signed in to change notification settings - Fork 0
/
insert_at_any_position.c
79 lines (65 loc) · 1.69 KB
/
insert_at_any_position.c
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
#include <stdio.h>
#include<stdlib.h>
//Represent a node of the singly linked list
struct node{
int data;
struct node *next;
};
//Represent the head and tail of the singly linked list
struct node *head, *tail = NULL;
//addNode() will add a new node to the list
void addNode(int data) {
//Create a new node
struct node *newNode = (struct node * )malloc( sizeof(struct node));
newNode->data = data;
newNode->next = NULL;
//Checks if the list is empty
if(head == NULL) {
//If list is empty, both head and tail will point to new node
head = newNode;
tail = newNode;
}
else {
//newNode will be added after tail such that tail's next will point to newNode
tail->next = newNode;
//newNode will become new tail of the list
tail = newNode;
}
}
void display() {
struct node *current = head;
if(head == NULL) {
printf("List is empty \n");
return;
}
while(current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
void insertanypos(int val,int pos){
struct node *current = head;
if(head == NULL) {
printf("List is empty \n");
return;
}
for(int i=0;i<pos-1;i++){
current = current->next;
}
current->data=val;
}
int main()
{
int n,x,p,data;
scanf("%d%d%d",&n,&x,&p);
for(int i=0;i<n;i++)
{
scanf("%d",&data);
addNode(data);
}
//display();
insertanypos(x,p);
display();
return 0;
}