链表
- 思路:
- 使用一个 dummy 指针迭代到 left;
- 然后反转 (right - left) 个 node;
- 之后将剩余的 node 继续串起来即可;
class Solution {
public:ListNode *reverseBetween(ListNode *head, int left, int right) {// 设置 dummyNode 是这一类问题的一般做法ListNode *dummyNode = new ListNode(-1);dummyNode->next = head;ListNode *pre = dummyNode;for (int i = 0; i < left - 1; i++) {pre = pre->next;}ListNode *cur = pre->next;ListNode *next;for (int i = 0; i < right - left; i++) {next = cur->next;cur->next = next->next;next->next = pre->next;pre->next = next;}return dummyNode->next;}
};