-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdesign_linked_list.cpp
120 lines (109 loc) · 2.93 KB
/
design_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
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
//program for design linked list
//problem link: https://leetcode.com/problems/design-linked-list/
class Node{
public:
int val;
Node * next, * prev;
Node(int val)
{
this -> val = val, this -> next = NULL, this -> prev = NULL;
}
};
class MyLinkedList {
public:
Node * head = NULL;
Node * tail = NULL;
int size = 0;
MyLinkedList() {
}
int get(int index) {
if(index >= size || index < 0) return -1;
else if(head == NULL) return -1;
else if(index == 0 ) return head -> val;
else if(index == size -1) return tail -> val;
Node * tmp = head;
for(int i = 1; i < index; i++)
{
tmp = tmp -> next;
}
return tmp -> next -> val;
}
void addAtHead(int val) {
size ++;
Node * newNode = new Node(val);
if(head == NULL)
{
head = newNode; tail = newNode;
return;
}
newNode -> next = head;
head -> prev = newNode;
head = newNode;
}
void addAtTail(int val) {
size ++;
Node * newNode = new Node(val);
if(head == NULL)
{
head = newNode;
tail = newNode;
return;
}
tail -> next = newNode;
newNode -> prev = tail;
tail = newNode;
}
void addAtIndex(int index, int val) {
if(index > size) return;
else if(index < 0) return;
else if(index == size)addAtTail(val);
else if(index == 0) addAtHead(val);
else{
Node * tmp = head;
Node * newNode = new Node(val);
for(int i = 1; i<index ; i++)
{
tmp = tmp -> next;
}
tmp -> next -> prev = newNode;
newNode -> next = tmp -> next;
newNode -> prev = tmp;
tmp -> next = newNode;
size ++;
}
}
void deleteAtIndex(int index) {
if(index < 0 || index >= size) return;
else if(head == NULL) return;
else if(index == 0)
{
Node * delNode = head;
head = head -> next;
if(head != NULL) head -> prev = NULL;
if(head == NULL) tail = NULL;
delete delNode;
size --;
}
else if(index == size -1)
{
Node * delNode = tail;
tail = tail -> prev;
tail -> next = NULL;
if(tail == NULL) head = NULL;
size --;
}
else
{
Node * tmp = head;
for(int i = 1; i < index; i++)
{
tmp = tmp -> next;
}
Node * delNode = tmp -> next;
if(tmp -> next -> next != NULL) tmp -> next -> next -> prev = tmp;
tmp -> next = tmp -> next -> next;
delete delNode;
size --;
}
}
};