leetcode : Reverse Linked List II
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+1个节点重新插入即可
注意,1:保存第一个被交换的节点以及最后一个被交换的节点的next指针
2: 如果m=1,则head将不再是链表的头结点!!!!!!
AC代码:
class Solution { public: ListNode *reverseBetween(ListNode *head, int m, int n) { if(!head) return NULL; auto H = new ListNode(0); H->next = head; for(int i = 0; i < m - 1; ++i) //H->next 指向第一个将要被交换的节点 H = H->next; auto p = H->next, prep = p; for(int i = 0; i <= n - m; ++i){ auto temp = p; p = p->next; temp->next = H->next; H->next = temp; } prep->next = p; return m == 1 ? H->next : head; } };
浙公网安备 33010602011771号