两个有序链表合并成一个新的链表,合成的链表一样有序排列

来源:互联网 发布:3d网络渲染花钱 编辑:程序博客网 时间:2024/05/16 11:06
#include<stdio.h>#include<malloc.h>#include<assert.h>typedef struct node{int data;struct node * next;}node;node * merge_insert( node * head1 ,  node * head2){node * head, *curhead, *tmphead, *prehead;assert(head1!=NULL && head2!=NULL);curhead=head1->data>=head2->data?head2:head1;tmphead=head1->data>=head2->data?head1:head2;head=curhead;prehead=curhead;curhead=curhead->next;while(curhead){while(tmphead){if(curhead->data >= tmphead->data){prehead->next=tmphead;tmphead=tmphead->next;prehead->next->next=curhead;prehead=prehead->next;}else{break;}}prehead=curhead;curhead=curhead->next;}prehead->next=tmphead;return head;} void print_merge(node * head) { assert(head!=NULL); while(head!=NULL) { printf("%d\t",head->data); head=head->next; } printf("\n"); }int main(){node a[5]={{1,NULL},{3,NULL},{4,NULL},{5,NULL},{6,NULL}},*p;node b[3]={{2,NULL},{5,NULL},{6,NULL}};a[0].next=&a[1];a[1].next=&a[2];a[2].next=&a[3];a[3].next=&a[4];b[0].next=&b[1];b[1].next=&b[2];p=merge_insert(&b[0],&a[0]);print_merge(p);}