反转链表 II:
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode* reverseBetween(ListNode* head, int m, int n) {
if (head == nullptr || m >= n) return head;
ListNode dummy(0);
dummy.next = head;
ListNode* prev_m = &dummy;
ListNode* prev_n = &dummy;
int count_m = m - 1;
int count_n = n;
while (count_m && prev_m != nullptr) {
prev_m = prev_m->next;
count_m--;
}
if (!prev_m || !prev_m->next) {
return head;
}
while (count_n && prev_n != nullptr) {
prev_n = prev_n->next;
count_n--;
}
ListNode* first = prev_m->next;
ListNode* last_next = prev_n->next;
ListNode* pre = last_next;
while (first != last_next) {
ListNode* next = first->next;
first->next = pre;
pre = first;
first = next;
}
prev_m->next = pre;
return dummy.next;
}
int main() {
ListNode* a = new ListNode(1);
ListNode* b = new ListNode(2);
ListNode* c = new ListNode(3);
ListNode* d = new ListNode(4);
ListNode* f = new ListNode(5);
ListNode* g = new ListNode(6);
a->next = b;
b->next = c;
c->next = d;
d->next = f;
f->next = g;
g->next = nullptr;
ListNode* result = reverseBetween(a, 3, 5);
while (result) {
cout << result->val << " ";
result = result->next;
}
return 0;
}