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 1: simple two pointer problem.
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode dummy=new ListNode(0);
dummy.next=head;
ListNode x=dummy, p=dummy, t=dummy;
for (int k=0; k<=n; k++) {
if (k==m-1) p=x;
if (k==n) t=x;
x=x.next;
}
ListNode i=p.next, j=t.next;
t.next=null;
while (i!=null) {
t=i.next;
i.next=j;
j=i;
i=t;
}
p.next=j;
return dummy.next;
}
}
没有评论:
发表评论