206. Reverse Linked List

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

iterative version

  1. try to think about making 1 -> NULL

  2. 1->2->3->4->5->NULL becomes NULL<-1 2->3->4->5->NULL

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode nHead = null;
        ListNode curr = head;
        
        while (curr != null) {
            ListNode nextTemp = curr.next; // store temp next
            curr.next = nHead; //link to reverse
            nHead = curr; // move (most left node first
            curr = nextTemp; //move
        }
        return nHead;
    }
}

Last updated