9月11日打卡:反转链表II

https://leetcode.cn/problems/reverse-linked-list-ii/description/?envType=problem-list-v2&envId=sUj8ubkb

image

 

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode() : val(0), next(nullptr) {}
 7  *     ListNode(int x) : val(x), next(nullptr) {}
 8  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 9  * };
10  */
11 class Solution {
12 public:
13     ListNode* reverseBetween(ListNode* head, int left, int right) {
14         //思路是区间[l,r]内反转,l-1与r相连,l与n-1相连
15        ListNode *dummy=new ListNode(-1,head);
16        head=dummy;
17        
18        ListNode *prev=NULL;//保存前驱
19 
20        for(int i=0;i<left-1;i++)    head=head->next;//先移动到left节点的前一个节点
21        ListNode *cur=head->next;//当前节点
22 
23        for(int i=0;i<right-left+1;i++){
24         ListNode *tmp=cur->next;//保存下一个节点防止丢失
25         cur->next=prev;//完成倒置
26         prev=cur;
27         cur=tmp;//移动到下一个节点
28        }
29 
30        head->next->next=cur;//反转开始的第一个节点连向倒数第二个节点
31        head->next=prev;//开始反转的前一个节点连向反转结束的节点
32        return dummy->next;
33     }
34 };

 

posted @ 2025-09-11 21:43  江上舟摇  阅读(9)  评论(0)    收藏  举报