#707

Design Linked List

expert · 1165 · lc medium +32 · 29.9% accepted · 3,049 likes · top 7%

Description

Implement a linked list from scratch. You may use a singly or doubly linked list. Nodes are 0-indexed.

Implement the MyLinkedList class:

- MyLinkedList() Creates an empty linked list.

- int get(int index) Returns the value at position index, or -1 if the index is out of bounds.

- void addAtHead(int val) Inserts a node with value val at the front of the list.

- void addAtTail(int val) Appends a node with value val to the end of the list.

- void addAtIndex(int index, int val) Inserts a node with value val before the node at position index. If index equals the list length, appends to the end. If index exceeds the length, does nothing.

- void deleteAtIndex(int index) Removes the node at position index if the index is valid.

Example 1:

Input
["MyLinkedList", "addAtHead", "addAtTail", "addAtIndex", "get", "deleteAtIndex", "get"]
[[], [1], [3], [1, 2], [1], [1], [1]]
Output
[null, null, null, null, 2, null, 3]

Example 2:

Explanation
MyLinkedList myLinkedList = new MyLinkedList();
myLinkedList.addAtHead(1);
myLinkedList.addAtTail(3);
myLinkedList.addAtIndex(1, 2); // linked list becomes 1->2->3
myLinkedList.get(1); // return 2
myLinkedList.deleteAtIndex(1); // now the linked list is 1->3
myLinkedList.get(1); // return 3

Code

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