AniUI Academy

A singly linked list you can reverse

mediumData Structures+250 XPPractice

A linked list stores each value in a node that points at the next one. Nothing needs to shift when you insert at the head, which is why lists show up inside schedulers, undo chains and the internals of frameworks.

Implement a LinkedList class. It is constructed with no arguments and starts empty. append(value) adds a value at the tail and returns the new length. prepend(value) adds a value at the head and returns the new length. get(index) returns the value at a zero-based index, or undefined when the index is negative or past the end. removeAt(index) removes the node at that index and returns its value, or returns undefined when the index is out of range. size() returns the number of values. toArray() returns the values as a plain array from head to tail, and [] when empty. reverse() reverses the list in place; its return value is not used.

Examples

const l = new LinkedList();
l.append("x"); // 1
l.append("y"); // 2
l.prepend("a"); // 3
l.toArray();   // ["a", "x", "y"]
const l = new LinkedList();
[1, 2, 3].forEach((v) => l.append(v));
l.removeAt(1); // 2 — removes the middle
l.toArray();   // [1, 3]
l.reverse();
l.toArray();   // [3, 1]

What it has to do

  • append and prepend return the length after the insertion.
  • get and removeAt return undefined for negative or out-of-range indices.
  • removeAt(0) works and keeps the rest of the list intact.
  • reverse() reverses in place and works on an empty list.
  • size() stays accurate after every insertion and removal.

Notes

  • prepend is O(1), but append, get and removeAt are O(n) without a tail pointer — walking the chain is unavoidable.
  • Reversing a singly linked list needs three pointers at once (previous, current, next). Lose track of next before you overwrite current.next and the tail of the list falls off a cliff.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +250 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.