Step 4 of 4

In-Place Reversal

You start from the build so far — your own work where you have written it, the reference build where you have not. Either way this step stands on its own.

Reversing a linked list is one of the classic interview questions.

Implement reverse() in-place using three pointers (prev, curr, next):

  1. Initialize prev = null and curr = this.head.
  2. Save this.tail = this.head (the original head becomes the new tail).
  3. Loop while curr !== null:
    • Store next = curr.next.
    • Reverse the pointer: curr.next = prev.
    • Advance: prev = curr, curr = next.
  4. Finally, set this.head = prev.

Your build

Running is free — Submit is what records the step. Or press ⌘↩

Tests

1 case
calltypeexpectedresult
runOps([["append",1],["append",2],["append",3],["append",4],["reverse"],["toArray"],["getAt",0],["getAt",3]])reverses non-empty linked list in-place[null,null,null,null,null,[4,3,2,1],4,1]

Hints

Stuck? Hints open one at a time, each giving a little more away.

2 hints left