力扣92.反转链表Ⅱ

 

将自己的思路记录一下

题目:【https://leetcode.cn/problems/reverse-linked-list-ii/description/?envType=study-plan-v2&envId=top-interview-150

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 struct ListNode* reverseBetween(struct ListNode* head, int left, int right) {
 9     if (left >= right)
10         return head;
11     struct ListNode* prev = NULL;
12     struct ListNode* curr = head;
13     struct ListNode* next = NULL;
14 
15     for (int i = 1; i < left; ++i) {
16         prev = curr;
17         curr = curr->next;
18     }
19     struct ListNode* start = curr;
20 
21     for (int i = 0; i <= right - left; ++i) {
22         next = curr->next;
23         curr->next = prev;
24         prev = curr;
25         curr = next;
26     }
27 
28     if (start->next) start->next->next = prev;
29     start->next = curr;
30     return left <= 1 ? prev : head;
31 }

 

另外记录一下自己第二次解这个题的思路

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 typedef struct ListNode ListNode_t;
 9 struct ListNode* reverseBetween(struct ListNode* head, int left, int right) {
10     if (!head->next || left == right)
11         return head;
12 
13     ListNode_t tmp;
14     ListNode_t* tn = &tmp;
15     tn->next = head;
16 
17     ListNode_t* th = tn;
18     for (int i = 0; i < left - 1; ++i)
19         th = th->next;
20 
21     ListNode_t* p = th->next;
22     ListNode_t* c = p->next;
23     ListNode_t* n = c;
24     for (int i = 0; i < right - left; ++i) {
25         n = n->next;
26         c->next = p;
27         p = c;
28         c = n;
29     }
30 
31     th->next->next = c;
32     th->next = p;
33 
34     th = tn->next;
35     return th;
36 }

 

posted @ 2025-02-07 14:16  J&YANG  阅读(11)  评论(0)    收藏  举报