链表合并 求两个递增链表的并

来源:互联网 发布:宝宝树软件 编辑:程序博客网 时间:2024/05/01 18:40
#include<iostream>#include<malloc.h>using namespace std;struct node{int data;node* next;};node* build(node* x){x=(node*)malloc(sizeof(node));node *y,*z;y=x;y->next=NULL;int n;cin>>n;while(n--){z=(node*)malloc(sizeof(node));cin>>z->data;y->next=z;y=z;y->next=NULL;}return x;}void print(node *z){z=z->next;while(z){cout<<z->data<<" ";z=z->next;}cout<<endl;}int main(){node *p=0,*q=0,*pre,*pa,*pb;p=build(p);q=build(q);pre=p;pa=p->next;pb=q->next;while(pa&&pb){if(pa->data<pb->data){pre=pa;pa=pa->next;}else if(pa->data==pb->data){pre=pa;pa=pa->next;pb=pb->next;}else {node* r;r=pb->next;pre->next=pb;pre=pb;pre->next=pa;pb=r;}}if(pb){pre->next=pb;}print(p);system("pause");return 0;}

0 0
原创粉丝点击