题目
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
思路
参考简书用户安全地带的解法https://www.jianshu.com/p/fbe6012c9e52
#include <cstddef>
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 == NULL) return NULL;
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* previous = dummy;
for (int i = 0; i < m - 1; i++)
{
previous = previous->next;
}
ListNode* current = previous->next;
ListNode* post = current->next;
for (int i = 0; i < n - m; i++)
{
current->next = post->next;
post->next = previous->next;
previous->next = post;
post = current->next;
}
return dummy->next;
}
};