Problem:
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
思路:
保存2个节点pre
和cur
,其中pre
指向第m-1个节点(从1开始算),而cur
指向第m个节点。在每次循环中,cur->next
指向的节点插入到pre
和pre->next
指向的节点中,然后经过操作cur->next = cur->next->next
后cur->next
指向的节点右移一位,经过n-m次操作后cur->next
指向第n+1个节点,然后经过n-m次插入操作后原本m后面的节点m+1到n节点倒序排列在m-1和m(现在的第n节点)节点之间。
Solution (C++):
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode *dummy = new ListNode(0), *pre = dummy, *cur;
dummy->next = head;
for (int i = 0; i < m - 1; ++i) {
pre = pre->next;
}
cur = pre->next; //pre指向第m-1个节点,cur指向第m个节点
for (int i = 0; i < n - m; ++i) { //每次循环时把第m+i+1个节点插入到(重新排列之后的)第m-1个节点和第m个节点之间
ListNode *tmp = pre->next;
pre->next = cur->next;
cur->next = cur->next->next;
pre->next->next = tmp;
}
return dummy->next;
}
性能:
Runtime: 4 ms Memory Usage: 8.9 MB