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
题目:将链表中的第m
到n
个结点反转。
思路:参考discuss。将第m-1
个结点记为pre
,第m
个结点记为cur
,那么反转即将第m+1
至第n
个结点依次插入pre
和pre->next
中。pre
和cur
未改变,只改变了pre->next
和cur->next
。如将第m+1
结点then=cur->next
插入pre
和pre->next
中时,先记录m+2
个点的位置,即cur->next = then->next
。然后将then->next
指向pre->next
,最后pre->next
指向then
。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode* dummy = new ListNode(0);
ListNode* pre = dummy;
pre->next = head;
for(int i = 1; i < m; ++i){
if(pre != nullptr)
pre = pre->next;
}
ListNode* cur = pre->next;
for(int i = m; i < n; ++i){
ListNode* next = cur->next;
cur->next = next->next;
next->next = pre->next;
pre->next = next;
}
return dummy->next;
}
};