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 {
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;
    }
};
posted @ 2022-08-24 10:39  hjy94wo  阅读(15)  评论(0)    收藏  举报