/**
* 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 *dummy = new ListNode(0); // 引入虚拟头节点
dummy->next = head;
ListNode *current = dummy;
while (current->next && current->next->next) {
ListNode *first = current->next;
ListNode *second = current->next->next;
// 交换操作
first->next = second->next;
second->next = first;
current->next = second;
// 移动到下一对需要交换的节点
current = first;
}
ListNode *newHead = dummy->next;
delete dummy; // 删除虚拟头节点
return newHead;
}
};
24. 两两交换链表中的节点
最新推荐文章于 2024-08-09 23:16:53 发布