Question
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.
本题难度Medium。
【复杂度】
时间 O(N) 空间 O(1)
【思路】
题目要求 Do it in-place and in one-pass. 采取的是 *(重点)[LeetCode]Reverse Nodes in k-Group的办法进行inverse节点。先移动m-1
次用before
指向需要inverse的首个节点之前的节点,然后利用cur、next、prev
对节点逐个进行inverse,完毕后这时before.next
指向的是目前的inverse区域内最后一个节点,prev
指向目前的inverse区域内的第一个节点,cur
指向区域外的第一个节点,最后利用:
before.next.next=cur;
before.next=prev;
完成inverse。
【注意】
本题需要用到fake。
【附】
本题与*(重点)[LeetCode]Reverse Nodes in k-Group不同在于本题的length>=n
,而那道题未必能。
【代码】
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
//require
ListNode fake=new ListNode(-1);
fake.next=head;
head=fake;
ListNode before=head;
for(int i=0;i<m-1;i++)
before=before.next;
//invariant
ListNode cur=before.next,prev=null,next=null;
for(int i=m;i<=n;i++){
next=cur.next;
cur.next=prev==null?null:prev;
prev=cur;
cur=next;
}
before.next.next=cur;
before.next=prev;
//ensure
return head.next;
}
}