字节跳动高频题——排序奇升偶降链表

步骤:

  1. 将链表拆分
  2. 链表逆序
  3. 链表合并

#include<iostream>
#include<random>
#include<queue>
using namespace std;
struct node{
    int val;
    node* next=NULL;
    node(int val_):val{val_}{}
};
node* create(vector<int> nums){
    if(nums.size()==0) return NULL;
    node* head=new node(nums[0]);
    node* tail=head;
    for(int i=1;i<nums.size();i++){
        tail->next=new node(nums[i]);
        tail=tail->next;
    }
    return head;
}
void show(node* head){
    node* t=head;
    while(t){
        cout<<t->val;
        t=t->next;
    }
}
vector<node*> split(node* head){
    vector<node*> res(2,NULL);//奇偶
    if(head==NULL) return res;
    res[0]=head;
    res[1]=head->next;
    node *odd=res[0],*even=res[1];
    while(even&&even->next){
        odd->next=even->next;
        odd=odd->next;
        even->next=odd->next;
        even=even->next;
    }
    odd->next=NULL;
    even->next=NULL;
    return res;

}
node* reve(node* head){
    if(head==NULL||head->next==NULL) return head;
    node* last=reve(head->next);
    head->next->next=head;
    head->next=NULL;
    return last;
}
struct cmp{
    operator()(node* n1,node* n2){
        return n1->val>n2->val;//n1如果是空
    }
};
node* merg(vector<node*> res){
    priority_queue<node*,vector<node*>,cmp> q;
    for(int i=0;i<2;i++)
        q.push(res[i]);
    node* h=q.top();
    q.pop();
    if(h->next!=NULL) q.push(h->next);

    node* tail=h;
    while(!q.empty()){
        tail->next=q.top();
        q.pop();
        tail=tail->next;
        if(tail->next!=NULL) q.push(tail->next);

    }

    return h;
}
int main()
{
    vector<int> nums{1,8,3,6,5,4,7,3,9,2};
    node* head=create(nums);
    vector<node*> res=split(head);
    res[1]=reve(res[1]);
    node* h=merg(res);
    show(h);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值