Home > AI > Data Structure > Linked List > Single Linked List >

leetcode-206-Reverse Linked List

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        
        while (head != null) {
            ListNode tmp = head.next; // divide current head from next parts;
            head.next = prev; // append previous result to current head;
            prev = head; // save to prev;
            head = tmp; // update the head;
        }
        
        return prev;
      
    }
}

Leave a Reply