-
Notifications
You must be signed in to change notification settings - Fork 0
/
Doubly linked list
105 lines (95 loc) · 1.63 KB
/
Doubly linked list
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
#include <iostream>
using namespace std;
struct Angka {
int value;
Angka *next;
Angka *prev;
}*head, *tail, *cur, *del, *newNode, *temp;
// Buat
void createDLL(int val) {
head = new Angka();
head->value = val;
head->next = NULL;
head->prev = NULL;
tail = head;
}
// Tambah
void addFirst(int val) {
newNode = new Angka();
newNode->value = val;
newNode->prev = NULL;
newNode->next = head;
head = newNode;
}
void addMid(int val, int index) {
newNode = new Angka();
newNode->value = val;
cur = head;
int count = 1;
while(count < index) {
cur = cur->next;
count++;
}
newNode->prev = cur;
newNode->next = cur->next;
cur->next = newNode;
cur = newNode->next;
cur->prev = newNode;
}
void addLast(int val) {
newNode = new Angka();
newNode->value = val;
newNode->prev = tail;
newNode->next = NULL;
tail->next = newNode;
tail = newNode;
}
// Hapus
void removeFirst() {
del = head;
head = del->next;
head->prev = NULL;
delete del;
}
void removeMid(int index) {
cur = head;
int count = 1;
while(count < index) {
cur = cur->next;
count++;
}
del = cur;
cur = cur->prev;
temp = del->next;
temp->prev = cur;
cur->next = temp;
delete del;
}
void removeLast() {
del = tail;
tail = tail->prev;
tail->next = NULL;
delete del;
}
void printDLL() {
cur = head;
int count = 1;
while(cur != NULL) {
std::cout << "value" << count << " : " << cur->value << std::endl;
cur = cur->next;
count++;
}
std::cout << "\n=====================================\n\n";
}
int main() {
createDLL(1);
for(int i = 2; i < 6; i++) {
addLast(i);
}
printDLL();
addMid(555, 3);
printDLL();
removeMid(3);
printDLL();
return 0;
}