pta7-3 两个有序链表序列的合并

#include<bits/stdc++.h>
using namespace std;
struct node{
    int data;
     node* next;
};
 node* createlist()
{
     node* head ,*end,*p;
    head=new struct node;
    end=head;
    end->next =NULL;
    int k;
    
    while(cin>>k&&k!=-1)
    {    p=new struct node;
        p->data=k;
        end->next=p;
        end=p;
     
    }
    end->next=NULL;
    return head->next;
    
}
node* operate( node* p1, node* p2)
{   
    if(!p1&&!p2)
    return NULL;
    else if(!p1)
    {
        return p2;
        
    }
    else if(!p2)
    {
        return p1;
    }
    else 
    {
          node* head ,*end;
         if(p1->data>=p2->data)
         {
             head=p2;
             end=p2;
             p2=p2->next;
         }
        else  if(p1->data<p2->data)
         {
             head=p1;
             end=p1;
             p1=p1->next;
         }         
         while(p1&&p2)
         {
             if(p1->data>=p2->data)
              {
             
                end->next=p2;
                 end=p2;
                 p2=p2->next;
              }
             else if(p1->data<p2->data)
             {
                 end->next=p1;
                 end=p1;
                 p1=p1->next;
              }
         
         }
         if(!p1)
         {
             end->next=p2;
         }
          else  if(!p2)
         {
             end->next=p1;
         }
        return head; 
    
    } 
    
}
int main()
{   int flag = 0;
    struct node*p1,*p2,*p3;
    p1=createlist();
    p2=createlist();
    p3=operate(p1,p2);
    if(!p3)
    { 
      cout<<"NULL";
    }
    else 
    {
        
    while(p3)
    {
        if(flag)printf(" %d",p3 -> data);
        else printf("%d",p3 -> data);
        p3= p3 -> next;
        flag = 1;
    }


    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值