Reverse Linked List II
https://leetcode.com/problems/reverse-linked-list-ii/description/
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.
Thoughts
基本思路不难想,从第m个开始翻转,要走到m - 1个,也就是跳m-2次next,然后从m开始翻转后面n - m + 1个nodes.
Corner cases很多,要加上m == 1 时相当于翻转整个链表。m== n时直接返回head.
Code
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if (m == n) return head;
auto cur = head;
if (m == 1) {
return reverse(head, n);
}
for (int i = 0; i < m - 2; ++i) {
cur = cur->next;
}
cur->next = reverse(cur->next, n - m + 1);
return head;
}
private:
ListNode* reverse(ListNode *head, int count) {
ListNode *cur = head, *prior = nullptr;
for (int i = 0; i < count; ++i) {
const auto next = cur->next;
cur->next = prior;
prior = cur;
cur = next;
}
head->next = cur;
return prior;
}
};Analysis
Errors:
翻转没用prior而是用的next算法,逻辑出现了混乱。
做题耗时: 1 hour
时间复杂度O(n), 空间O(1).
Last updated
Was this helpful?