两个有序链表的合并##C语言

#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct res)
struct res{
    int x ;
    int y ;
    struct res *next;//递归定义
};
struct res *creat ( int n ) {
    struct res *head , *p1 , *p2 ;
    for(int i = 1 ; i <= n ; i++ ){
        p1 = ( struct res * ) malloc ( LEN ) ;
        scanf("%d%d" , &p1->x , &p1->y) ;
        if ( i == 1 ) head = p1 ;
        else p2->next = p1 ;
        p2 = p1 ;
        p1->next = NULL;
    }
    return (head) ;
}
void print ( struct res *head ) {
    struct res *p = head ;
    while( p != NULL ){
        printf("%d %d\n", p->x,p->y);
        p = p->next;
    }
}
struct res *link(struct res *head1 ,struct res *head2){ 
     if ( head1 == NULL ) return ( head2 ) ;//是否为空链表
     if ( head2 == NULL ) return ( head1 ) ;
     //确定头指针
     else {
         struct res *head , *p1 , *p2 ;
        p1 = head1 ;
        p2 = head2 ;
         if ( head1->y <= head2->y ) {
         head = head1;
         p1 = p1->next ;
         }
        else {//if ( head1->y > head2->y ) 
         head = head2;
         p2 = p2->next ;
        }
     //定义move指针遍历
       struct res *move = head ;
       while ( p1 && p2 ){
            if ( p1->y <= p2->y ) {
             move->next = p1 ;
             move = p1 ;
             p1 = p1->next ;
         }
         else {  //if ( p1->y > p2->y )
             move->next = p2 ;
             move = p2 ;
             p2 = p2->next ;
         }
     }
     //连接剩余链表
     if ( p1 ) move->next = p1 ;
     if ( p2 ) move->next = p2 ;
    return ( head ) ;
     }
}
int main(){
    int n , m ;
    struct res *head1 , *head2 ;
    
    printf("input first res number:\n") ; 
    
    scanf("%d", &n );
    
    printf("input x and y: \n");
    
    head1 = creat(n);
    
    printf("input second res number:\n") ; 
    
    scanf("%d",  &m );
    
    printf("input x and y :\n");
    
    head2 = creat(m); 
    
    printf( "\n" ) ;
    
    print (    link( head1 , head2 ) ) ;
    
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值