-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdoubly_linked_list.cpp
93 lines (72 loc) · 1.89 KB
/
doubly_linked_list.cpp
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
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *prev;
Node *next;
Node(int data_) {
data = data_;
}
};
class DLL {
public:
Node *head;
DLL() {
head = nullptr;
}
void print() {
Node *curr = head;
while (curr != nullptr) {
cout << curr -> data << " ";
curr = curr -> next;
}
cout << "\n";
}
void reversePrint() {
Node *curr = head;
while (curr -> next != nullptr) {
curr = curr -> next;
}
while (curr != nullptr) {
cout << curr -> data << " ";
curr = curr -> prev;
}
cout << "\n";
}
void insertAtHead(int data) {
// create a new Node object
Node *newNode = new Node(data);
// if list is not initialized, then set the first node as head of the list
if (head == nullptr) {
head = newNode;
return;
}
head -> prev = newNode;
newNode -> next = head;
head = newNode;
}
void insertAtTail(int data) {
// create a new Node
Node *newNode = new Node(data);
if (head == nullptr) {
head = newNode;
return;
}
Node *curr = head;
while (curr -> next != nullptr) {
curr = curr -> next;
}
curr -> next = newNode;
newNode -> prev = curr;
}
};
int main() {
DLL *list = new DLL();
list -> insertAtHead(0);
list -> insertAtHead(1);
list -> insertAtTail(100);
list -> insertAtTail(101);
list -> print();
return 0;
}