数据结构04——单链表的归并

题目:输入两个数字n,m;

输入非递减有序单链顺序表A(元素为n个);输入非递减单链有序顺序表B(元素为m个)。

将A,B合并为非递增有序单链顺序表C并输出。(要求用原表空间存放C)

输入样例:5 5

                 1 3 7 12 16

                 2 6 7 13 20

输出样例:20 16 13 12 7 7 6 3 2 1

#include<stdio.h>  
#include<stdlib.h>  

typedef struct node{  
        int num;  
        node* next;  
    }node; 

node* init(int x){
	int i;
	node *head,*p,*q;
	
	head=(node*)malloc(sizeof(node));
	q=head;
	while(x--){
		p=(node*)malloc(sizeof(node));
		scanf("%d",&(p->num));
		q->next=p;
		q=p;
	}
	q->next=NULL;
	return head;
}

node* unio(node* x,node* y){
	node *p,*q,*t,*r,*head;
	head=(node*)malloc(sizeof(node));
	r=head;
	p=x->next;
	q=y->next;
	
	while(p&&q){
		if(p->num < q->num){
			r->next=p;
			r=p;
			p=p->next;
		}
		else{
			r->next=q;
			r=q;
			q=q->next;
		}
	}
	if(p){
		r->next=p;
		r=p;
		p=p->next;
	}
	else if(q){
		r->next=q;
		r=q;
		q=q->next;
	}
	else{
		r->next=NULL;
	}
	return head;
}

node* down(node* head){
	node *p,*q;
	p=head->next;  
    head->next=NULL;   
    while(p){  
        q=p;  
        p=p->next;  
        q->next=head->next;  
        head->next=q;  
    }  
    q=head->next;
    return head;
}
int main(){  
    int n,m,k,i;  
      
     
    node *head1,*head2,*p,*q,*r,*t;  
      
    scanf("%d%d",&n,&m);  
    head1=init(n);
	head2=init(m);
	head1=unio(head1,head2);
	head1=down(head1);
	r=head1->next;  
    while(r){  
        if(r->next==NULL){  
            printf("%d\n",r->num);    
        }  
        else{  
            printf("%d ",r->num);
		}
        r=r->next;    
    } 
    return 0;  
}  

猜你喜欢

转载自blog.csdn.net/chengchencheng/article/details/79708312