Skip to content

Commit 0c29b6a

Browse files
committed
707. Design Linked List
1 parent 3334b04 commit 0c29b6a

File tree

1 file changed

+97
-0
lines changed

1 file changed

+97
-0
lines changed

design-linked-list.cpp

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
// Runtime: 48 ms
2+
// Memory Usage: 19.5 MB
3+
class MyLinkedList {
4+
public:
5+
6+
class Node {
7+
public:
8+
int val;
9+
Node* next;
10+
Node* prev;
11+
12+
Node(int val) {
13+
this->val = val;
14+
this->next = NULL;
15+
this->prev = NULL;
16+
}
17+
};
18+
19+
Node* head;
20+
Node* tail;
21+
int len;
22+
MyLinkedList() {
23+
head = new Node(-1);
24+
tail = new Node(-1);
25+
head->next = tail;
26+
tail->prev = head;
27+
len = 0;
28+
}
29+
30+
31+
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
32+
int get(int index) {
33+
if (index >= len || index < 0) return -1;
34+
int i = 0;
35+
Node* crawl = head->next;
36+
while (i++ < index && crawl)
37+
crawl = crawl->next;
38+
if (!crawl) return -1;
39+
return crawl->val;
40+
}
41+
42+
/** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
43+
void addAtHead(int val) {
44+
Node* newNode = new Node(val);
45+
newNode->next = head->next;
46+
head->next->prev = newNode;
47+
newNode->prev = head;
48+
head->next = newNode;
49+
len++;
50+
}
51+
52+
/** Append a node of value val to the last element of the linked list. */
53+
void addAtTail(int val) {
54+
Node* newNode = new Node(val);
55+
newNode->next = tail;
56+
newNode->prev = tail->prev;
57+
tail->prev->next = newNode;
58+
tail->prev = newNode;
59+
len++;
60+
}
61+
62+
/** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
63+
void addAtIndex(int index, int val) {
64+
if (index > len) {
65+
return;
66+
} else if (index < 0) {
67+
addAtHead(val);
68+
} else {
69+
int i = 0;
70+
Node* crawl = head->next;
71+
while (i++ < index && crawl)
72+
crawl = crawl->next;
73+
if (!crawl) return;
74+
Node* newNode = new Node(val);
75+
crawl->prev->next = newNode;
76+
newNode->next = crawl;
77+
newNode->prev = crawl->prev;
78+
crawl->prev = newNode;
79+
len++;
80+
}
81+
82+
}
83+
84+
/** Delete the index-th node in the linked list, if the index is valid. */
85+
void deleteAtIndex(int index) {
86+
if (index >= len || index < 0) return;
87+
int i = 0;
88+
Node* crawl = head->next;
89+
while (i++ < index && crawl)
90+
crawl = crawl->next;
91+
92+
if (!crawl) return;
93+
crawl->prev->next = crawl->next;
94+
crawl->next->prev = crawl->prev;
95+
len--;
96+
}
97+
};

0 commit comments

Comments
 (0)