剑指offer- 题目1519:合并两个排序的链表 (2014.1.3)

12 篇文章 0 订阅
 #include <iostream>
#include <string>
#include <stdio.h>
#include <vector>
using   namespace   std;
struct   Entry
{
     int   m;
     Entry *next;
};
Entry *GetNewEntry(){
     int   p;
     cin>>p;
     Entry *newOne= new   Entry;
     newOne->m=p;
     newOne->next=NULL;
     return   newOne;
}
Entry *BuildList( int   n)
{
     Entry *listHead=NULL;
     Entry *p=NULL;
     while   (n>0)
     {
         Entry *newOne=GetNewEntry();
         n--;
         if   (p==NULL)
         {
             p=newOne;
             listHead=p;
         } else {
             p->next=newOne;
             p=p->next;
         }
         
     }
     return   listHead;
}
Entry *mergeList(Entry *list1,Entry *list2) //递归实现
{
     if   (list1==NULL)
     {
         return   list2;
     }
     else   if   (list2==NULL)
     {
         return   list1;
     }
     Entry *list=NULL;
     if (list1->m<=list2->m)
     {
         list=list1;
         list->next=mergeList(list1->next,list2);
     } else {
         list=list2;
         list->next=mergeList(list1,list2->next);
     }
     return   list;
}
void   PrintEntry(Entry *m)
{
     cout<<m->m;
}
void   PrintList(Entry *list)
{
     if   (list==NULL){
         cout<<endl;
     } else {
         PrintEntry(list);
         if   (list->next!=NULL)
         {
             cout<< " " ;
         }
         PrintList(list->next);
     }
}
int   main()
{
     int   m,n;
     while   (cin>>m>>n)
     {
         if (m==0&&n==0){
             cout<< "NULL" <<endl;
         } else {
             vector< int > strList;
             Entry *p=BuildList(m);
             Entry *q=BuildList(n);
             Entry *list=mergeList(p,q);
             PrintList(list);
         }
     }
     return   0;
}
/**************************************************************
     Problem: 1519
     User: 无梦楼主lv
     Language: C++
     Result: Accepted
     Time:450 ms
     Memory:4688 kb
****************************************************************
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值