Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given
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.
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
Solution:O(n)
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head==null || head.next == null)
return head;
ListNode pre = new ListNode(0);
pre.next=head;
head=pre;
ListNode n1=head;
int k=m-1;
while(k>0){
n1=n1.next;
k--;
}
pre=n1;
n1=n1.next;
k=n-m;
while(n1.next!=null && k>0){
ListNode tmp =n1.next;
n1.next=tmp.next;
tmp.next=pre.next;
pre.next=tmp;
k--;
}
return head.next;
}
}
Key Concept: pre ... n1 tmp
沒有留言:
張貼留言