-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02_Doble_Linked_List.cpp
More file actions
144 lines (125 loc) · 2.64 KB
/
02_Doble_Linked_List.cpp
File metadata and controls
144 lines (125 loc) · 2.64 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
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#include <stdio.h>
#include <stdlib.h>
struct Node{
int value;
Node *next, *prev;
}*head, *tail;
Node *createNewNode(int value) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->value = value;
newNode->next = newNode->prev = NULL;
return newNode;
}
void pushHead(int value) {
Node *temp = createNewNode(value);
if(!head) {
head = tail = temp;
} else {
head->prev = temp;
temp->next = head;
head = temp;
}
}
void pushTail(int value) {
Node *temp = createNewNode(value);
if(!head) {
head = tail = temp;
} else {
tail->next = temp;
temp->prev = tail;
tail = temp;
}
}
void pushMid(int value) {
if(!head) {
Node *temp = createNewNode(value);
head = tail = temp;
} else if(value < head->value) {
pushHead(value);
} else if(value > tail->value) {
pushTail(value);
} else {
Node *temp = createNewNode(value);
Node *curr = head;
while(curr->value < value) {
curr = curr->next;
}
temp->prev = curr->prev;
temp->next = curr;
curr->prev->next = temp;
curr->prev = temp;
}
}
void popHead() {
if(!head) {
return;
} else if(head == tail) {
free(head);
head = tail = NULL;
} else {
Node *temp = head->next;
head->next = head->prev = NULL;
free(head);
head = temp;
}
}
void popTail() {
if(!head) {
return;
} else if(head == tail) {
free(head);
head = tail = NULL;
} else {
Node *temp = tail->prev;
tail->prev = temp->next = NULL;
free(tail);
tail = temp;
}
}
void popMid(int value) {
if(!head) {
return;
} else if(head->value == value) {
popHead();
} else if(tail->value == value) {
popTail();
} else {
Node *curr = head;
while(curr && curr->value != value) {
curr = curr->next;
}
curr->prev->next = curr->next;
curr->next->prev = curr->prev;
curr->prev = curr->next = NULL;
free(curr);
curr = NULL;
}
}
void printLL() {
Node *curr = head;
printf("Double Linked List:\n");
while(curr != NULL) {
printf("%d <-> ", curr->value);
curr = curr->next;
}
puts("NULL");
}
int main() {
pushHead(3);
pushHead(1);
printLL();
pushTail(6);
pushTail(9);
printLL();
pushMid(7);
printLL();
pushMid(4);
printLL();
popHead();
printLL();
popTail();
printLL();
popMid(6);
printLL();
return 0;
}