Lintcode36: 翻转链表 II

描述

翻转链表中第m个节点到第n个节点的部分

m,n满足1 ≤ m ≤ n ≤ 链表长度

样例

给出链表1->2->3->4->5->null, m = 2 和n = 4,返回1->4->3->2->5->null

挑战

在原地一次翻转完成

思路:这道题以前做过,好久没碰了,居然思路又忘了,。。

首先我们在头节点前面插入一个节点,那样头节点就可以看作中间节点了,不需要额外考虑其他情况了。

然后就是交换两个相邻节点之间的next指针了,这一步需要记录三个节点的信息,具体可以自己画下就知道过程了。

Java代码如下:

public static ListNode reverseBetween(ListNode head, int m, int n) {
        // write your code here
        if(m>=n || head == null){
            return head;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy;
        for (int i = 1; i < m; i++) {
            head = head.next;
        }
        ListNode p_pre = head;
        ListNode p_end = head.next;

        // m<-->n 互换
        ListNode w1 = head.next;
        ListNode w2 = w1.next;
        for (int i = m; i < n; i++) {
            if(w2 == null){
                return null;
            }
            ListNode temp = w2.next;
            w2.next = w1;
            w1 = w2;
            w2 = temp;
        }
        p_pre.next = w1;
        p_end.next = w2;
        return dummy.next;
    }

猜你喜欢

转载自blog.csdn.net/u012156116/article/details/80657959