- 反转链表 II
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
补充:C语言版本
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseBetween(struct ListNode* head, int m, int n){
if (NULL == head || NULL == head->next || m == n) {
return head;
}
struct ListNode* pre = NULL;
struct ListNode* cur = head;
while (m > 1) {
pre = cur;
cur = cur->next;
m--;
n--;
}
struct ListNode* start = pre;
struct ListNode* tail = cur;
while (n > 0) {
struct ListNode* next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
n--;
}
if (NULL == start) {
head = pre;
} else {
start->next = pre;
}
tail->next = cur;
return head;
}
/*0ms,5.4MB*/
思路一:递归法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
ListNode* successor = NULL;
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if (head == NULL || head->next == NULL || m == n){
return head;
}
if (m == 1){
return reverseN(head, n);
}
head->next = reverseBetween(head->next, m - 1, n - 1);
return head;
}
ListNode* reverseN(ListNode* head, int n) {
if (head == NULL || head->next == NULL){
return head;
}
if (n == 1){
successor = head->next;
return head;
}
ListNode* last = reverseN(head->next, n - 1);
head->next->next = head;
head->next = successor;
return last;
}
};
/*0ms,9.9MB*/
时间复杂度: O(n)
空间复杂度: O(n)
思路二:迭代法
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if (head == NULL || head->next == NULL || m == n){
return head;
}
ListNode* pre = NULL;
ListNode* cur = head;
while (m > 1){
pre = cur;
cur = cur->next;
m--;
n--;
}
ListNode* pStart = pre;
ListNode* tail = cur;
while(n > 0){
ListNode* next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
n--;
}
if (NULL != pStart){
pStart->next = pre;
} else {
head = pre;
}
tail->next = cur;
return head;
}
};
/*0ms,9.8MB*/
时间复杂度: O(n)
空间复杂度: O(1)
参考链接:
https://leetcode-cn.com/problems/reverse-linked-list-ii/solution/fan-zhuan-lian-biao-ii-by-leetcode/