力扣 24. 两两交换链表中的节点 链表+递归

38 篇文章 0 订阅
20 篇文章 0 订阅

https://leetcode-cn.com/problems/swap-nodes-in-pairs/
在这里插入图片描述

思路一:顺着做,这样也有两种做法。第一种就是直接两个两个交换,那么需要记录前驱和后继。第二种就是先把链表分成两个小的链表,一个存储奇数位置的树,一个存储偶数位置的数,然后再把他们合起来。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(!head||!head->next)
            return head;
        ListNode *pre,*cur=head,*nxt=head->next;
        cur->next=nxt->next;
        nxt->next=cur;
        head=nxt;
        pre=cur;
        while(pre){
            cur=pre->next;
            if(!cur||!cur->next)
                break;
            nxt=cur->next;
            cur->next=nxt->next;
            nxt->next=cur;
            pre->next=nxt;
            pre=cur;
        }
        return head;
    }
};
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* merge(ListNode* l,ListNode *r){
        ListNode head(0);
        ListNode *res=&head;
        bool flag=1;
        while(l&&r){
            if(flag){
                res->next=l;
                res=l;
                l=l->next;
            }
            else{
                res->next=r;
                res=r;
                r=r->next;
            }
            flag=!flag;
        }
        res->next=l?l:r;
        return head.next;
    }
    ListNode* swapPairs(ListNode* head) {
        if(!head||!head->next)
            return head;
        ListNode odd(0),even(0);
        ListNode *tail1=&odd,*tail2=&even,*cur=head;
        bool flag=1;
        while(cur){
            if(flag)
                tail1->next=cur,tail1=cur;
            else
                tail2->next=cur,tail2=cur;
            cur=cur->next;
            flag=!flag;
        }
        tail1->next=tail2->next=nullptr;
        return merge(even.next,odd.next);
    }
};

思路二:递归。思路其实和上面的差不多,但是代码相当简洁。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(!head||!head->next)
            return head;
        ListNode *cur=head;
        ListNode *nxt=head->next;
        cur->next=swapPairs(nxt->next);
        nxt->next=cur;
        return nxt;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值