网址: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(0); ListNode* a = NULL; ListNode* b = new ListNode(0); ListNode* c = new ListNode(0); ListNode* fake_h = new ListNode(0); fake_h->next = head; ListNode* temp = fake_h; int i = 1; for(; i<m-1; 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-1; 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; } };