24. 两两交换链表中的节点 - 力扣(LeetCode)
题解:
- 迭代
首先是直接遍历的做法,这里注意调整指针指向的顺序。
/*** 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* swapPairs(ListNode* head) {ListNode * dummyHead = new ListNode(0);dummyHead -> next = head;ListNode * tmp = dummyHead;ListNode*first, *second; // 反转前后用到的临时节点while(tmp->next!=nullptr && tmp->next->next!=nullptr){first = tmp->next;second = tmp->next->next;// 先调整tmp,再调整 first,再调整 secondtmp -> next = second;first -> next = second -> next;second -> next = first;tmp = first;}ListNode * ans = dummyHead -> next;delete dummyHead;return ans;}
};
- 递归
递归的本质在于直接处理最小子集。
/*** 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* swapPairs(ListNode* head) {if(head == nullptr || head -> next == nullptr){return head;}ListNode *newHead = head -> next;head -> next = swapPairs(newHead -> next);newHead -> next = head;return newHead;}
};