两两交换链表中的结点

发布时间 2023-04-26 10:54:34作者: 该说不唠

题目:给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。

你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换

 

 步骤:

 

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode* dummyHead = new ListNode(0); // 设置一个虚拟头结点
        dummyHead->next = head; // 将虚拟头结点指向head,这样方面后面做删除操作
        ListNode* cur = dummyHead;
        while(cur->next != nullptr && cur->next->next != nullptr)
    { ListNode
* tmp = cur->next; // 记录临时节点,保存结点1 ListNode* tmp1 = cur->next->next->next; // 记录临时节,保存结点3 cur->next = cur->next->next; // 步骤一,注意位置会相对的改变 cur->next->next = tmp; // 步骤二 cur->next->next->next = tmp1; // 步骤三 cur = cur->next->next; // cur移动两位,准备下一轮交换 } return dummyHead->next; } };
需要注意的点:
其中判断条件:while(cur->next != nullptr && cur->next->next !=
nullptr)
要考虑奇偶的情况,为奇数时,cur->next为空指针,如果就是空链表,也适用
为偶数时,cur->next->next为空指针
并且
cur->next != nullptr 与 cur->next->next != nullptr不能交换位置,因为如果cur->next为空的话,cur->next->next会出现空指针异常的情况