力扣24. 两两交换链表中的节点

 

 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* reverse(ListNode *head) {
14          if (!head || !head -> next) {
15             return head;
16         }
17         ListNode *pre = head, *cur = head -> next, *nxt = cur -> next;
18         pre -> next = nullptr;
19         cur -> next = pre;
20         return nxt; //返回下一组的头节点
21     }
22     ListNode* swapPairs(ListNode* head) {
23         if (!head || !head -> next) {
24             return head;
25         }
26         ListNode *tail = head -> next;
27         ListNode *nxt = reverse(head);
28         head -> next = swapPairs(nxt);
29         return tail;
30     }
31 };

 

posted on 2025-03-13 16:06  Coder何  阅读(6)  评论(0)    收藏  举报