反转链表 II
问题描述
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
- 输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
Code
时间复杂度O(n),空间复杂度O(1)
/**
* 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 *prev = &dummy;
for(int i = 0; i < m - 1; ++i)
prev = prev->next;
ListNode* const head2 = prev;
prev = head2->next;
ListNode *cur = prev->next;
for(int i = m; i < n; ++i){
prev->next = cur->next;
cur->next = head2->next;
head2->next = cur;
cur = prev->next;
}
return dummy.next;
}
};
若有疑问欢迎评论!