代码随想录:两两交换链表中的节点

代码随想录:两两交换链表中的节点

链表题目务必用虚头节点,很多问题会变简单很多

/**
 * 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) {
        ListNode* virt = new ListNode;
        virt->next = head;
        ListNode* target = head;
        ListNode* tail = virt;

        while (target != NULL && target->next != NULL) {
            tail->next = target->next;
            ListNode* n = target->next->next;
            ListNode* node2 = target->next;

            target->next = n;
            node2->next = target;
            tail = target;
            target = n;
        }
        return virt->next;
    }
};
posted @ 2024-11-19 22:30  huigugu  阅读(1)  评论(0编辑  收藏  举报