2个有序链表的合并

来源:互联网 发布:斑马网络计划破解软件 编辑:程序博客网 时间:2024/05/21 18:16
#include<iostream>using namespace std;typedef struct head{int a;struct head *next;}NLode;void intial(NLode **head){*head=(NLode *)malloc(sizeof(NLode));(*head)->next=NULL;}void insert(NLode *head,int a){NLode *p,*q;p=head;q=(NLode*)malloc (sizeof(NLode));while(p->next!=NULL){p=p->next;}q->a=a;q->next=p->next;p->next=q;}NLode *Merge(NLode *head1,NLode *head2){if(head1->next==NULL)return head2;if(head2->next==NULL)return head1;NLode *head3,*p1,*p2,*p3,*p;head3=(NLode *)malloc(sizeof(NLode));p1=head1->next;p2=head2->next;p3=head3;while(p1!=NULL &&p2!=NULL){if(p1->a>p2->a){p=(NLode*)malloc(sizeof(NLode));p->next=NULL;p->a=p2->a;p3->next=p;p3=p3->next;p2=p2->next;}else{    p=(NLode*)malloc(sizeof(NLode));p->next=NULL;p->a=p1->a;p3->next=p;p3=p3->next;p1=p1->next;}}while(p1!=NULL){p=(NLode*)malloc(sizeof(NLode));p->next=NULL;p->a=p1->a;p3->next=p;p3=p3->next;p1=p1->next;}while(p2!=NULL){   p=(NLode*)malloc(sizeof(NLode));   p->next=NULL;p->a=p2->a;p3->next=p;p3=p3->next;p2=p2->next;}return head3;}void printSL(NLode *head){NLode *p;p=head->next;while(p!=NULL){cout<<p->a<<"   ";p=p->next;}}void main(){NLode *head1,*head2,*head3; intial(&head1);intial(&head2);int a,b,num=0,i;cin>>a;cin>>b;for(i=0;i<a;i++){cin>>num;insert(head1,num);}num=0;for(i=0;i<b;i++){cin>>num;insert(head2,num);}head3=Merge(head1,head2);cout<<"A:"<<endl;printSL(head1);cout<<endl;cout<<"B:"<<endl;printSL(head2);cout<<endl;cout<<"C:"<<endl;printSL(head3);cout<<endl;system("pause");}

0 0
原创粉丝点击