Implement Doubly Linked List
EasyP2Coding
Implement a doubly linked list of integers. Each node holds a value, a prev link and a next link. Do not use an array or list to hold the elements.
Implement the DoublyLinkedList class (indices start at 0):
DoublyLinkedList()creates an empty list.addAtHead(val)inserts a new first node.addAtTail(val)appends a new last node.addAtIndex(index, val)inserts a node so that it becomes the node at positionindex. Ifindexequals the length it appends; ifindexis greater than the length, do nothing.deleteAtIndex(index)removes the node atindexif it is valid, otherwise does nothing.get(index)returns the value atindex, or-1if the index is invalid.toList()returns all values from head to tail.toListReversed()returns all values from tail to head, by following theprevlinks.
Negative indices are invalid. Operations at the head or tail must be O(1).
Example 1
- Input
- ["DoublyLinkedList","addAtHead","addAtTail","addAtIndex","toList","toListReversed","get","deleteAtIndex","toList","toListReversed"] [[],[1],[3],[1,2],[],[],[1],[1],[],[]]
- Output
- [null,null,null,null,[1,2,3],[3,2,1],2,null,[1,3],[3,1]]
- Why
- Both traversals must agree, which checks that prev and next are kept in sync.
Constraints
- 0 <= index <= 1000 (may exceed the length)
- -1000 <= val <= 1000
- At most 2000 calls in total.
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 2 visible tests, Submit all 8. ⌘Enter runs, ⌘⇧Enter submits.