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.
本题是链表翻转的进阶版,要求随意翻转链表的一部分。其实难度上并没有大很多,我们只需要找到第m和第n个节点即可,然后剩下的链表翻转操作就和之前题目的思路一样了。代码入下所示:
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode dummyhead = new ListNode(0);
dummyhead.next = head;
ListNode sublisthead = new ListNode(0);
ListNode sublisttail = new ListNode(0);
int count = 1;
ListNode pre_cur = dummyhead, cur = head;
while(count <=n){
ListNode temp = cur.next;
if (count < m)
pre_cur = cur;
else if (count == m){
sublisttail = cur;
sublisthead.next = cur;
}else if (count > m){
cur.next = sublisthead.next;
sublisthead.next = cur;
}
cur = temp;
++count;
}
pre_cur.next = sublisthead.next;
sublisttail.next = cur;
return dummyhead.next;
}