-
Notifications
You must be signed in to change notification settings - Fork 2
/
insert_at_nth_position.c
130 lines (97 loc) · 2.05 KB
/
insert_at_nth_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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include<stdio.h>
#include<stdlib.h>
struct Node {
int data;
struct Node* next;
struct Node* prev;
} *head, *tail;
typedef struct Node node;
void insertFirst(int data) {
node *newNode = (node*) (malloc(sizeof(node)));
newNode -> data = data;
newNode -> prev = NULL;
if(head == NULL) {
head = tail = newNode;
tail->next = NULL;
}
else {
newNode->next = head;
head->prev = newNode;
head = newNode;
}
}
void insertLast(int item) {
node * newNode;
newNode = (node*) malloc(sizeof(node));
newNode -> data = item;
newNode -> next = NULL;
if(head == NULL) {
head = tail = newNode;
head -> prev = NULL;
}
else {
tail->next = newNode;
newNode->prev = tail;
tail = newNode;
}
}
void insert_at_position(int data, int pos) {
int i = 1;
node *temp = head;
while(i < pos-1 && temp != tail) {
temp = temp->next;
i++;
}
if(pos == 1) {
insertFirst(data);
}
else if(temp == tail) {
insertLast(data);
}
else {
node *newNode;
newNode = (node*) malloc(sizeof(node));
newNode->data = data;
newNode->next = temp->next;
newNode->prev = temp;
if(temp->next != NULL) temp->next->prev = newNode;
temp->next = newNode;
}
}
void display() {
node * temp;
temp = head;
printf("Printing forward...\n");
while(temp != NULL) {
printf("%d ", temp->data);
// tail = temp;
temp = temp->next;
}
printf("\n");
printf("Printing backward...\n");
temp = tail;
while(temp != NULL) {
printf("%d ", temp->data);
temp = temp->prev;
}
printf("\n");
}
int main() {
insertFirst(4);
insertFirst(3);
insertLast(5);
insertLast(7);
insertFirst(2);
insert_at_position(1, 1);
insert_at_position(6, 6);
insert_at_position(8, 8);
display();
return 0;
}
/*
Output:
Printing forward...
1 2 3 4 5 6 7 8
Printing backward...
8 7 6 5 4 3 2 1
*/