LINKEDLIST

92. Reverse Linked List II

2017-03-24  本文已影响17人  DrunkPian0

Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

这题看了答案,在纸上写了一遍思路还蛮清晰的。我发现Leetcode自己的solutions里面的高票答案就挺好的(https://discuss.leetcode.com/topic/8976/simple-java-solution-with-clear-explanation)。

思想:

这题思想是一直让start绕过它后面的节点then,接到then.next上去,然后then接到逆序list的首位,也就是pre.next。

注意的地方:

for循环中的第二句then.next应该指向pre.next,而不是start。
因为start和then一直在向右平移,交换过一次后pre已经不会指向start。

draft
    public ListNode reverseBetween(ListNode head, int m, int n) {
        // we need for nodes
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode pre = dummy;
        ListNode start;
        ListNode then;
        for (int i = 0; i < m - 1; i++) {
            pre = pre.next;
        }

        start = pre.next;
        then = start.next;

        for (int i = 0; i < n - m; i++) {//交换n-m次
            start.next = then.next;
            then.next = pre.next; //it has to be pre.next,而不是start,因为start和then一直在向右平移,交换过一次后pre已经不会指向start
            pre.next = then;
            then = start.next;
        }

        return dummy.next;
    }

今天是周五。买了一台iPhone。

上一篇 下一篇

猜你喜欢

热点阅读