-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path707-Design-Linked-List.cpp
More file actions
126 lines (103 loc) · 2.52 KB
/
707-Design-Linked-List.cpp
File metadata and controls
126 lines (103 loc) · 2.52 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
#define IOS ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(0);
class MyLinkedList {
struct ListNode {
int val;
ListNode* next;
};
private:
ListNode* head;
ListNode* tail;
public:
MyLinkedList() {
head = tail = nullptr;
}
int get(int index) {
IOS
ListNode* ptr = head;
int i = 0;
while (ptr) {
if (i == index)
return ptr->val;
i++;
ptr = ptr->next;
}
return -1;
}
void addAtHead(int val) {
IOS
ListNode* newNode = new ListNode;
newNode->val = val;
newNode->next = head;
head = newNode;
if (tail == nullptr)
tail = newNode;
}
void addAtTail(int val) {
IOS
ListNode* newNode = new ListNode;
newNode->val = val;
newNode->next = nullptr;
if (tail == nullptr) {
head = tail = newNode;
return;
}
tail->next = newNode;
tail = newNode;
}
void addAtIndex(int index, int val) {
IOS
if (index == 0) {
addAtHead(val);
return;
}
ListNode* newNode = new ListNode;
newNode->val = val;
ListNode* ptr = head;
int i = 0;
while (i < index - 1 && ptr) {
i++;
ptr = ptr->next;
}
if (ptr == nullptr)
return;
newNode->next = ptr->next;
ptr->next = newNode;
if (newNode->next == nullptr)
tail = newNode;
}
void deleteAtIndex(int index) {
IOS
if (head == nullptr)
return;
if (index == 0) {
ListNode* temp = head;
head = head->next;
delete temp;
if (head == nullptr)
tail = nullptr;
return;
}
ListNode* ptr = head;
int i = 0;
while (ptr && i < index - 1) {
i++;
ptr = ptr->next;
}
if (!ptr || !ptr->next)
return;
ListNode* temp = ptr->next;
ptr->next = ptr->next->next;
delete temp;
if (!ptr->next)
tail = ptr;
}
};
/**
* Your MyLinkedList object will be instantiated and called as such:
* MyLinkedList* obj = new MyLinkedList();
* int param_1 = obj->get(index);
* obj->addAtHead(val);
* obj->addAtTail(val);
* obj->addAtIndex(index,val);
* obj->deleteAtIndex(index);
*/