206. Reverse Linked List

Reverse a singly linked list.
A linked list can be reversed either iteratively or recursively. Could you implement both?

Solution1a:Iterative 依次reverse

思路: 依次reverse: 1 -> 2 -> 3 -> 4
1 <- 2 -> 3 -> 4 再 1 <- 2 <- 3 -> 4 再 1 <- 2 <- 3 <- 4
Time Complexity: O(N) Space Complexity: O(1)

Solution1b:Iterative (前部)插入法reverse

(当然后部也行,这里前部比较方便不用先知道结尾)
思路: 前部插入法reverse: 1 -> 2 -> 3 -> 4
2 -> 1 -> 3 -> 4 再 3 -> 2 -> 1 -> 4 再 4 -> 3 -> 2 -> 1

206. Reverse Linked List_第1张图片
屏幕快照 2017-09-11 下午9.55.44.png

Solution2:Recursive

思路2: 先pre-order处理当前level,再recursively处理后序level,注意找到recursion后序和当前的传递关系:需要依赖前一个的prev
backwards回传return:new_head

206. Reverse Linked List_第2张图片
屏幕快照 2017-09-12 上午12.15.07.png

Time Complexity: O(N) Space Complexity: O(1)

Solution1a Code:

class Solution1a {
    public ListNode reverseList(ListNode head) {
        ListNode cur = head, prev = null;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
        }
        return prev;
    }
}

Solution1b Code:

class Solution {
    public ListNode reverseList(ListNode head) {
        // is there something to reverse?
        if(head == null || head.next == null) return head;
        
        ListNode cur = head;
        while (cur.next != null)
        {
            ListNode post = cur.next;
            cur.next = cur.next.next;
            post.next = head;
            head = post;
        }

        return head;
    }
}

Solution1b Round1 改了good变量名字 Code:
pre将cur抛到起始作为head

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null) return head;
        
        ListNode pre = head;
        while(pre.next != null) {
            ListNode cur = pre.next;
            pre.next = cur.next;
            cur.next = head;
            head = cur;
        }
        
        return head;
    }
}

Solution2 Code:

class Solution {
    public ListNode reverseList(ListNode head) {
        /* recursive solution */
        return reverseListInt(head, null);
    }

    private ListNode reverseListInt(ListNode cur, ListNode prev) {
        if (cur == null)
            return prev;
        
        // deal with current level
        ListNode next = cur.next;
        cur.next = prev;
        
        // input: recursion needs next_cur=next, next_prev=head, 
        // collect(return): and needs to return(upload backwards) new_head 
        ListNode new_head = reverseListInt(next, cur);
        
        return new_head;
    }
}

你可能感兴趣的:(206. Reverse Linked List)