题目描述
题目链接:92. Reverse Linked List II
Reverse a linked list from position m to n. Do it in one-pass.
例子
例子 1
Input:
1->2->3->4->5->NULL, m = 2, n = 4
Output:1->4->3->2->5->NULL
Note
- 1 ≤ m ≤ n ≤ length of list.
解题思路
这道题在逆转链表的基础上添加一个范围,要求只翻转一定范围的链表,其他部分保持不变,并且要求只遍历一次。逆转链表的方法可以参考 [Leetcode]206. Reverse Linked List(C++),主要利用 prev
, curr
和 next
三个指针进行操作。这里只需要用一个 step
找到翻转的起始和结束位置即可,注意通过这样翻转之后,假如我们讲链表分成三部分:
- 第一部分不变 (1~m-1)
- 第二部分需要反转 (m ~ n)
- 第三部分不变 (n + 1 ~)
注意,通过这样的方法到最后 prev
会指向第 n
个节点,作为第二部分反转的后的头,curr
会指向第 n + 1
个节点作为第三部分的头,但我们还需要保存第一部分的尾部以及第二部分的尾部以便进行连接。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode* dummy = new ListNode();
dummy->next = head;
ListNode *first_tail, *second_head, *second_tail;
ListNode *curr = dummy, *prev, *next;
int step = 1;
// move curr to the node just before the mth node, mark it as tail for the first part
// and mth node should be tail for second part
while (step < m) {
curr = curr->next;
step++;
}
first_tail = curr;
curr = curr->next;
second_tail = curr;
prev = curr;
curr = curr->next;
while (step < n) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
step++;
}
first_tail->next = prev;
second_tail->next = curr;
return dummy->next;
}
};
- 时间复杂度: O(n)
- 空间复杂度: O(1)
GitHub 代码同步地址: 92.ReverseLinkedListIi.cpp
其他题目: GitHub: Leetcode-C++-Solution 博客: Leetcode-Solutions