Doubly Linked List - Problem
Implement a doubly linked list with bidirectional traversal, insertion, and deletion operations at any position.
Your doubly linked list should support the following operations:
insertAtHead(val)- Insert a new node with given value at the beginninginsertAtTail(val)- Insert a new node with given value at the endinsertAtIndex(index, val)- Insert a new node at the specified indexdeleteAtIndex(index)- Delete the node at the specified indexget(index)- Get the value of the node at the specified indextoArray()- Return all values as an array for testing
The doubly linked list should maintain both forward and backward pointers, allowing efficient bidirectional traversal.
Input & Output
Example 1 — Basic Operations
$
Input:
operations = [["insertAtHead", 1], ["insertAtTail", 2], ["insertAtIndex", 1, 3], ["get", 0], ["toArray"]]
›
Output:
[null, null, null, 1, [1, 3, 2]]
💡 Note:
insertAtHead(1) → list: [1], insertAtTail(2) → list: [1,2], insertAtIndex(1,3) → list: [1,3,2], get(0) returns 1, toArray() returns [1,3,2]
Example 2 — Delete Operations
$
Input:
operations = [["insertAtHead", 5], ["insertAtTail", 10], ["deleteAtIndex", 0], ["toArray"]]
›
Output:
[null, null, null, [10]]
💡 Note:
insertAtHead(5) → list: [5], insertAtTail(10) → list: [5,10], deleteAtIndex(0) removes first element → list: [10], toArray() returns [10]
Example 3 — Invalid Index
$
Input:
operations = [["insertAtHead", 7], ["get", 5], ["deleteAtIndex", 10], ["toArray"]]
›
Output:
[null, -1, null, [7]]
💡 Note:
insertAtHead(7) → list: [7], get(5) returns -1 (invalid index), deleteAtIndex(10) does nothing (invalid index), toArray() returns [7]
Constraints
- 1 ≤ operations.length ≤ 1000
- -1000 ≤ val ≤ 1000
- 0 ≤ index ≤ size
- get() returns -1 for invalid indices
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code