LeetCode刷题笔记 24. 两两交换链表中的节点

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

题目要求

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

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

示例:

给定 1->2->3->4, 你应该返回 2->1->4->3.

题解

https://github.com/soulmachine/leetcode

画个图秒懂。

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head==nullptr||head->next==nullptr) return head;
        ListNode dummy(-1);
        dummy.next=head;

        for(ListNode *prev=&dummy,*cur=prev->next,*next=cur->next;
            next;
            prev=cur,cur=cur->next,next=cur?cur->next:nullptr
        ){
            prev->next=next;
            cur->next=next->next;
            next->next=cur;
        }
        return dummy.next;
    }
};

递归法

https://leetcode-cn.com/problems/swap-nodes-in-pairs/comments/
By mata川

精妙啊!

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head==nullptr||head->next==nullptr) return head;
        ListNode* next=head->next;
        head->next=swapPairs(next->next);     
        next->next=head;
        return next;        
    }
};
发布了18 篇原创文章 · 获赞 0 · 访问量 1806

猜你喜欢

转载自blog.csdn.net/g534441921/article/details/104128334