leetcode——第24题——两两交换链表中的节点

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

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换

/**
 * 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 {
/*
1、处理链表,记着虚拟头结点的使用,将cur记为虚拟头结点,不然每次还要针对头结点做单独处理。

*/

public:
    ListNode* swapPairs(ListNode* head) 
    {
        // 设置虚拟头结点,并将其指向头结点
        ListNode* dummyHead = new ListNode(0);
        dummyHead->next = head;

        // 注意对节点的操作不能直接在 设置的虚拟头结点上进行,还需再定义一个临时变量
        ListNode* cur = dummyHead;

        // 这里的条件也需要注意,要保证接下来的两个节点是非空才可以
        while(cur->next != nullptr && cur->next->next != nullptr)
        {
            // 这里要记录两个临时节点
            ListNode* temp1 = cur->next; // 临时节点1
            ListNode* temp2 = cur->next->next->next;    // 临时节点2

            cur->next = temp1->next;    // 三次转换
            cur->next->next = temp1;
            cur->next->next->next = temp2;

            cur = cur->next->next;
        }
        return dummyHead->next;
    }
};
经验分享 程序员 微信小程序 职场和发展