-
Notifications
You must be signed in to change notification settings - Fork 160
/
design-linked-list.md
41 lines (33 loc) · 2.64 KB
/
design-linked-list.md
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
<p>Design your implementation of the linked list. You can choose to use the singly linked list or the doubly linked list. A node in a singly linked list should have two attributes: <code>val</code> and <code>next</code>. <code>val</code> is the value of the current node, and <code>next</code> is a pointer/reference to the next node. If you want to use the doubly linked list, you will need one more attribute <code>prev</code> to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed.</p>
<p>Implement these functions in your linked list class:</p>
<ul>
<li><code>get(index)</code> : Get the value of the <code>index</code>-th node in the linked list. If the index is invalid, return <code>-1</code>.</li>
<li><code>addAtHead(val)</code> : Add a node of value <code>val</code> before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.</li>
<li><code>addAtTail(val)</code> : Append a node of value <code>val</code> to the last element of the linked list.</li>
<li><code>addAtIndex(index, val)</code> : Add a node of value <code>val</code> before the <code>index</code>-th node in the linked list. If <code>index</code> 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.</li>
<li><code>deleteAtIndex(index)</code> : Delete the <code>index</code>-th node in the linked list, if the index is valid.</li>
</ul>
<p> </p>
<p><strong>Example:</strong></p>
<pre>
<b>Input: </b>
["MyLinkedList","addAtHead","addAtTail","addAtIndex","get","deleteAtIndex","get"]
[[],[1],[3],[1,2],[1],[1],[1]]
<b>Output: </b>
[null,null,null,null,2,null,3]
<b>Explanation:</b>
MyLinkedList linkedList = new MyLinkedList(); // Initialize empty LinkedList
linkedList.addAtHead(1);
linkedList.addAtTail(3);
linkedList.addAtIndex(1, 2); // linked list becomes 1->2->3
linkedList.get(1); // returns 2
linkedList.deleteAtIndex(1); // now the linked list is 1->3
linkedList.get(1); // returns 3
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= index,val <= 1000</code></li>
<li>Please do not use the built-in LinkedList library.</li>
<li>At most <code>2000</code> calls will be made to <code>get</code>, <code>addAtHead</code>, <code>addAtTail</code>, <code>addAtIndex</code> and <code>deleteAtIndex</code>.</li>
</ul>