LeetCode-92.反转链表II(相关话题:链表)

反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。

说明:

1 ≤ m ≤ n ≤ 链表长度。

示例:

输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL

Java代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if(m == n)
            return head;

        ListNode p = new ListNode(0), q, pre = p, suf;
        int cnt = m;
        p.next = head;
        head = p;
        while(--cnt > 0){
            pre = pre.next;
        }

        suf = pre.next;
        p = pre.next;
        q = p.next;
        while(m++ < n){
            ListNode tmp = q.next;
            q.next = p;
            p = q;
            q = tmp;
        }

        pre.next = p;
        suf.next = q;

        return head.next;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_38823568/article/details/82845172