Skip to main content

Command Palette

Search for a command to run...

Reverse Linked List

Published
•1 min read•View as Markdown

The trick to this problem...

you need a runner node, a previous node, and nextTemp node.

First initialize your prev node and runner node.

//given ListNode head , reverse the linked list

ListNode prev = null;
ListNode run = head;

Now we want to iterate through entire list until the runner is null.

  1. next temp node equals the next node *point
  2. runner next equals the previous node *point
  3. prev node equals run *reassign
  4. run equals next temp *reassign
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode run= head;
        while (run!= null) {
            ListNode nextTemp = run.next;
            run.next = prev;
            prev = curr;
            run= nextTemp;
        }
        return prev;
    }
}