首页 > 其他分享 >LeetCode 24. 两两交换链表中的节点

LeetCode 24. 两两交换链表中的节点

时间:2022-08-24 10:44:45浏览次数:69  
标签:24 ListNode cur val int res next 链表 LeetCode

/**
 * 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* res = new ListNode(0);
        res ->next = head;
        ListNode* cur = res;
        

        while (cur ->next && cur ->next ->next) {
            ListNode* temp1 = cur ->next;
            ListNode* temp2 = cur ->next ->next -> next;

            cur ->next = cur ->next ->next;
            cur ->next ->next = temp1;
            cur ->next ->next ->next = temp2;

            cur = cur ->next ->next;

        }

        return res ->next;
    }
};

标签:24,ListNode,cur,val,int,res,next,链表,LeetCode
From: https://www.cnblogs.com/hjy94wo/p/16619007.html

相关文章