[ Web Proxy ]
URL:
Viewing: https://raw.githubusercontent.com/git-jhy/JavaArithmetic/master/src/LeetCode/LeetCode206.java [Back]  [Original]

package LeetCode;

public class LeetCode206 {

    // https://leetcode.com/problems/reverse-linked-list/description/
    // : O(n)
    // : O(1)

    // Definition for singly-linked list.
    public class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }

    public ListNode reverseList(ListNode head) {

        ListNode pre = null;
        ListNode cur = head;
        while(cur != null){
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }

        return pre;
    }

    // 
    public ListNode reverseList2(ListNode head) {

        // 
        if(head == null|| head.next == null)
            return head;

        // head==1  --->head==2 return head ==2
        ListNode rhead = reverseList2(head.next);

        // head->nexthead
        // head->next->next = headhead

        // TODO 
        head.next.next = head;

        // null
        head.next = null;

        return rhead;
    }
}

Web Proxy Viewer  |  New URL  |  Original Page