lc21-合并两个有序链表

#include<stdio.h>
#include<iostream>
using namespace std;
typedef struct node{
    int data;
    node *next;
}linklist;
linklist *mergeTwoLists(linklist *head1,linklist *head2){
    linklist *head,*p;
    head=(linklist*)malloc(sizeof(linklist));
    head1=head1->next;
    head2=head2->next;
    p=head;
    while(head1!=NULL&&head2!=NULL){
        if(head1->data<head2->data){
            p->next=head1;
            head1=head1->next;
            p=p->next;
        }
        else{
            p->next=head2;
            head2=head2->next;
            p=p->next;
        }
    }
    if(head1!=NULL){
        p->next=head1;
    }
    if(head2!=NULL){
        p->next=head2;
    }
    return head;
}
void main(){
        int n,m;
    scanf("%d%d",&n,&m);
    linklist *head1,*k1,*head2,*k2,*head;
    head1=(linklist*)malloc(sizeof(linklist));
    head1->next=NULL;
    k1=head1;
    for(int i=0;i<n;i++){
        linklist *p;
        p=(linklist*)malloc(sizeof(linklist));
        scanf("%d",&p->data);
        p->next=k1->next;
        k1->next=p;
        k1=p;

    }
    head2=(linklist*)malloc(sizeof(linklist));
    head2->next=NULL;
    k2=head2;
    for(int i=0;i<n;i++){
        linklist *p;
        p=(linklist*)malloc(sizeof(linklist));
        scanf("%d",&p->data);
        p->next=k2->next;
        k2->next=p;
        k2=p;

    }
    head=(linklist*)malloc(sizeof(linklist));
    head=mergeTwoLists(head1,head2);
    while(head->next!=NULL){
        printf("%d",head->next->data);
        head=head->next;
    }

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容