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的元素。
解法:先向后移动m个元素,再和之前的反转链表一样的操作。
/**
* 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(-1);
dummy.next = head;
ListNode *pre = &dummy;
for(int i = 0; i < m-1; ++i)
pre = pre->next;
ListNode *head2 = pre;
pre = pre->next;
ListNode *cur = pre->next;
for(int i = m; i < n; ++i){
pre->next = cur->next;
cur->next = head2->next;
head2->next = cur;
cur = pre->next;
}
return dummy.next;
}
};