24. 两两交换链表中的节点
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
// 使用哨兵节点简化头节点的交换逻辑
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* current = dummy;
while (current->next != nullptr && current->next->next != nullptr) {
ListNode* first = current->next;
ListNode* second = first->next;
// 进行节点交换
first->next = second->next;
second->next = first;
current->next = second;
// 移动指针,准备下一对交换
current = first;
}
// 保存新的头节点
ListNode* newHead = dummy->next;
delete dummy; // 释放哨兵节点
return newHead;
}
};