算法系列——反转链表II(Reverse Linked List II)

110 阅读1分钟

题目描述

题目链接:leetcode-cn.com/problems/re…

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.

解题思路

经典的题目就是链表区间内进行逆序,采用头插法。

程序实现

class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode dummy=new ListNode(-1);
        dummy.next=head;
        ListNode prev=dummy;
        ListNode cur=head;
        for(int i=1;i<left;i++){
            prev=cur;
            cur=cur.next;
        }
        //此时 prev 指向 m-1 cur指向 m 
        //头插法 将 cur后的结点链接到 prev 的后面 成为新的头
        for(int i=left;i<right;i++){
            ListNode tmp=cur.next;
            cur.next=tmp.next;
            tmp.next=prev.next;
            prev.next=tmp;
        }
        return dummy.next;
    }
}