24. 两两交换链表中的节点
https://leetcode.cn/problems/swap-nodes-in-pairs/description/
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
/**
* 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 || !head->next)
return head;
ListNode *p1 = head, *p2, *new_head = nullptr;
while (p1 && p1->next) {
p2 = p1->next;
p1->next = p2->next;
p2->next = p1;
// 定义新头节点
if (!new_head) {
new_head = p1;
head = p2;
} else {
new_head->next = p2;
new_head = p1;
}
//
p1 = new_head->next;
}
if (p1 && !p1->next) {
new_head->next = p1;
}
return head;
}
};