Reverse a singly linked list in place by rewiring next
An undo history, a playlist queue, and a chain of middleware can all be stored as a singly linked list. Each node points only to the next one, so reading the list backwards means rewiring it.
Implement reverseList(head). It reverses the list in place and returns the new head.
reverseList(head) // => the new head node, or null
Every node is a plain object with a value and a next pointer. The last node has next: null. An empty list is null.
{ value: 'intro.mp3', next: { value: 'verse.mp3', next: { value: 'outro.mp3', next: null } } }
next pointers. Do not create new nodes and do not change value or any other property.next must be null. The result must not contain a cycle.null for an empty list.// 'intro.mp3' -> 'verse.mp3' -> 'outro.mp3'
const reversed = reverseList(playlist);
// 'outro.mp3' -> 'verse.mp3' -> 'intro.mp3'
reversed.value; // => 'outro.mp3'
reversed.next.next === playlist; // => true (the old head is now last)
playlist.next; // => null
reverseList({ value: 42, next: null });
// => the same node: { value: 42, next: null }
reverseList(null);
// => null
null, objects, and duplicates.