1-b. 链表逆序2 【92】(medium)
#include <iostream>
using namespace std;
/*
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
*/
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
}; // namespace stddstructListNode
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode* dummy = new ListNode(-1);
dummy->next = head;
ListNode* p = dummy;
// Find the m-1 th node
for (int i = 1; i < m; ++i) {
p = p->next;
}
ListNode* prev = p;
ListNode* curr = p->next;
ListNode* tail = curr;
// Reverse from m to n
for (int i = m; i <= n; ++i) {
ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
// Connect three parts
p->next = prev;
tail->next = curr;
return dummy->next;
}
// 递归
// ListNode *successor = new ListNode(-1); // 后驱节点
// // 反转以 head 为起点的 n 个节点,返回新的头结点
// ListNode *reverseN(ListNode *head, int n) {
// if (n == 1) {
// // 记录第 n + 1 个节点
// successor = head->next;
// return head;
// }
// // 以 head.next 为起点,需要反转前 n - 1 个节点
// ListNode *last = reverseN(head->next, n - 1);
// head->next->next = head;
// // 让反转之后的 head 节点和后面的节点连起来
// head->next = successor;
// return last;
// }
// ListNode *reverseBetween(ListNode *head, int m, int n) {
// // base case
// if (m == 1) {
// return reverseN(head, n);
// }
// // 前进到反转的起点触发 base case
// head->next = reverseBetween(head->next, m - 1, n - 1);
// return head;
// }
};
int main() {
ListNode a(1);
ListNode b(2);
ListNode c(3);
ListNode d(4);
ListNode e(5);
a.next = &b;
b.next = &c;
c.next = &d;
d.next = &e;
Solution solve;
ListNode* head = solve.reverseBetween(&a, 2, 4);
while (head) {
cout << head->val << endl;
head = head->next;
}
return 0;
}