合并两个有序链表 押题卷

#include <stdio.h>
#include <stdlib.h>
struct node{
    int data;
    struct node *next;
};
struct node *creat1(int a[],int n){
    struct node *head,*tail,*s;
    int i;
    head = (struct node *)malloc(sizeof(struct node));
    head->data=a[0];
    head->next=NULL;
    tail=head;
    for (int i = 1; i < n; ++i) {
        s=(struct node *)malloc(sizeof(struct node));
        s->data = a[i];
        s->next = NULL;
        tail->next=s;
        tail=s;
    }
    return head;
}
struct node *combine(struct node *p,struct node *q){
    struct node *h,*t;
    if(p->data<=q->data){
        h=p;t=p;p=p->next;
    }
    else{
        h=q;t=q;q=q->next;
    }
    while (p!=NULL && q!=NULL){
        if (p->data<=q->data){
            t->next=p;t=p;p=p->next;
        } else{
            t->next=q;t=q;q=q->next;
        }
    }
    if (p==NULL)
        t->next=q;
    else
        t->next=p;
    return h;
}
void print(struct node *p){
    while (p!=NULL){
        printf("%d,",p->data);
        p=p->next;
    }
    printf("\n");
}
int main(){
    int a[10]={1,3,5,7,9,12,18,20,25,30},b[6]={4,6,10,12,14,230};
    struct node *head,*head1,*head2;
    printf("Creat list A:\n");
    head1=creat1(a,10);
    printf("Creat list B:\n");
    head2=creat1(b,6);
    printf("Output list A:\n");
    print(head1);
    printf("Output list B:\n");
    print(head2);
    printf("Combine list A and list B:\n");
    head=combine(head1,head2);
    printf("Output list after combine list A and list B:\n");
    print(head);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值