92. 反转链表 II
给你单链表的头指针
head
和两个整数 left
和 right
,其中 left <= right
。请你反转从位置 left
到位置 right
的链表节点,返回 反转后的链表 。
示例 1:
输入:head = [1,2,3,4,5], left = 2, right = 4 输出:[1,4,3,2,5]
示例 2:
输入:head = [5], left = 1, right = 1 输出:[5]
提示:
- 链表中节点数目为
n
1 <= n <= 500
-500 <= Node.val <= 500
1 <= left <= right <= n
进阶: 你可以使用一趟扫描完成反转吗?
解析:
分为left == right
left == head
left != head
找到left的前驱
从left + 1 开始 前驱头插即可
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* reverseBetween(ListNode* head, int left, int right) { if(left == right) return head; if(left == 1) { ListNode* p = head; int cnt = 2; while(cnt <= right) { ListNode* temp = p->next; p->next = p->next->next; temp->next = head; head = temp; cnt++; } } else { int cnt = 1; ListNode* p = head; while(cnt < left - 1) p = p->next, cnt++; ListNode* q = p; p = p->next, cnt += 2; while(cnt <= right) { ListNode* temp = p->next; p->next = p->next->next; temp->next = q->next; q->next = temp; cnt++; } } return head; } };