链表归并
# include <stdio.h> # include <malloc.h> # include <string.h> typedef struct node { struct node *next; int data; }LINK; LINK *merge(LINK *head1,LINK *head2); int main() { int i,n,m; LINK *q,*p,*head,*head1,*head2,*tail1,*tail2; head1=(LINK *)malloc(sizeof(LINK)); head2=(LINK *)malloc(sizeof(LINK)); head1->next=NULL; head2->next=NULL; tail1=head1; tail2=head2; scanf("%d%d",&n,&m); for(i=0;i<n;i++) { p=(LINK *)malloc(sizeof(LINK)); scanf("%d",&p->data); tail1->next=p; tail1=p; } for(i=0;i<m;i++) { p=(LINK *)malloc(sizeof(LINK)); scanf("%d",&p->data); tail2->next=p; tail2=p; } tail1->next=NULL; tail2->next=NULL; head=merge(head1,head2); p=head->next; for(i=0;i<m+n;i++) { if(i)printf(" "); printf("%d",p->data); p=p->next; } printf("\n"); return 0; } LINK *merge(LINK *head1,LINK *head2) { LINK *p1,*p2,*tail; p1=head1->next; p2=head2->next; tail=head1; free(head2); while(p1 && p2) { if(p1->data < p2->data) { tail->next=p1; tail=p1; p1=p1->next; } else { tail->next=p2; tail=p2; p2=p2->next; } } if(p1) tail->next=p1; else tail->next=p2; return head1; }