92. Reverse Linked List II 反转链表 II

时间:2021-09-04 15:32:20

网址:https://leetcode.com/problems/reverse-linked-list-ii/

核心部分:通过a、b、c三个变量之间的相互更新,不断反转部分链表

然后将反转部分左右两端接上!

当测试数据 m 为 1 时,原始代码行不通。

故我们在原head前加一个fake_h节点,在函数部分将m++,n++,最后return fake_h->next

注意判断head为空 和 不反转任何部分(m==n)这两种情况

/**
* 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)
{
if(!head->next || m==n)
{
return head;
}
m++;
n++;
ListNode* pre = NULL;
ListNode* first = new ListNode();
ListNode* a = NULL;
ListNode* b = new ListNode();
ListNode* c = new ListNode();
ListNode* fake_h = new ListNode();
fake_h->next = head;
ListNode* temp = fake_h;
int i = ;
for(; i<m-; i++)
temp = temp->next;
pre = temp;
first = pre->next;
b = pre->next;
c = b->next;
cout << "b: " << b->val << endl;
cout << "c: " << c->val << endl;
for(; i<n-; i++)
{
b->next = a;
a = b;
cout << "a: " << a->val << endl;
b = c;
c = c->next;
}
b->next = a;
cout << "pre: " << pre->val << endl;
pre->next = b;
first->next = c;
return fake_h->next;
}
};

92. Reverse Linked List II 反转链表 II