链表两两交换

题目链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/
题目描述:
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。


回顾:链表反转
题解:


/**
 * 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* dummy = new ListNode(0);
        dummy->next = head;      //链入头节点,dummy为头节点
        ListNode* cur = dummy;  //初始时cur指向头节点, cur为要交换节点的前继节点
        while(cur->next != nullptr && cur->next->next != nullptr)
        {
            ListNode* post = cur->next;
            ListNode* temp = post->next->next;

            cur->next = post->next;
            post->next->next = post;
            post->next = temp;
    
            cur = cur->next->next;   //cur向后移动两个节点
        }
        return dummy->next;
        

    }
};

posted @ 2021-05-13 14:41  张宵  阅读(195)  评论(0编辑  收藏  举报