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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
class { public ListNode reverseBetween(ListNode head, int m, int n) { if(m==n || head==null) return head; ListNode dummy=new ListNode(0); dummy.next=head; ListNode pre=dummy; for(int i=0;i<m-1;i++) { pre=pre.next; } ListNode start=pre.next; ListNode then=start.next; for(int i=0;i<n-m;i++) { start.next = then.next; then.next = prev.next; prev.next = then; then = start.next; } return dummy.next; } }
|
TIPS:
画图,判断条件时要注意~
近期评论