
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (head == NULL || head->next == NULL ) return head;
ListNode* dumhead = new ListNode(0);
dumhead->next = head;
ListNode* pre = dumhead;
ListNode* curNode = head;
while (curNode->next) {
ListNode* next = curNode->next;
curNode->next = next->next;
next->next = curNode;
pre->next = next;
pre = curNode;
if (curNode->next) curNode = curNode->next;
}
head = dumhead->next;
delete dumhead;
return head;
}
};
int main()
{
Solution sol;
vector<int> input1 = {1,2,3,4,5,6};
ListNode *head = createListNode(input1);
printLinkedList(sol.swapPairs(head));
deleteLinkedList(head);
return 0;
}

本文介绍了一种使用C++实现的链表中相邻节点的交换算法。通过创建虚拟头节点简化边界条件,遍历链表并交换每对相邻节点的位置,最终返回修改后的链表头。该算法适用于计算机科学和数据结构的学习。
740

被折叠的 条评论
为什么被折叠?



