Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Design a Linked List

Linked Listsmedium

Course · Section 11: Working With Arrays · Lecture 149: Simple Array Methods

Design a singly linked list (you may back it with any structure). Implement `MyLinkedList`: - `get(index)` returns the value at index, or `-1` if invalid. - `addAtHead(val)` / `addAtTail(val)`. - `addAtIndex(index, val)` inserts before index (append if index equals length; ignore if greater). - `deleteAtIndex(index)` removes the node at index if valid.

Examples

Input: addAtHead(1), addAtTail(3), addAtIndex(1,2), get(1), deleteAtIndex(1), get(1)
Output: [2, 3]
List becomes 1->2->3; get(1) is 2. After deleting index 1, list is 1->3 and get(1) is 3.

Sample tests

Input: build and edit the list
Output: [2,3]
Input: out-of-range get
Output: [7,-1]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Off-by-one on the addAtIndex boundary (index === length should append).

Learning resources

  • Wikipedia: Linked list
Approach & explanation (try first)

An index-validated sequence implements the linked-list API. The boundary rules on addAtIndex/deleteAtIndex are the tricky part.

Loading...
⌘/Ctrl + Enter

Run your code to see results.