zoukankan      html  css  js  c++  java
  • 【剑指Offer面试编程题】题目1519:合并两个排序的链表--九度OJ

    题目描述:

    输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
    (hint: 请务必使用链表。)

    输入:

    输入可能包含多个测试样例,输入以EOF结束。
    对于每个测试案例,输入的第一行为两个整数n和m(0<=n<=1000, 0<=m<=1000):n代表将要输入的第一个链表的元素的个数,m代表将要输入的第二个链表的元素的个数。
    下面一行包括n个数t(1<=t<=1000000):代表链表一中的元素。接下来一行包含m个元素,s(1<=t<=1000000)。

    输出:

    对应每个测试案例,
    若有结果,输出相应的链表。否则,输出NULL。

    样例输入:

    5 2
    1 3 5 7 9
    2 4
    0 0
    样例输出:

    
    
    1 2 3 4 5 7 9
    NULL
    【解题思路】本题应该是非常经典题目了,当然链表数据结构的实现也算是一个考点。主题思路当然将两个链表输入然后,利用两个指针分别指向两个链表表头,一次比较两个指针的值,谁小谁前进,直达有指针到达链表的尾部停止比较。将剩余的值依次链入目标链表中,完成链表的合并。

         本题中还是利用了stl中list实现,没有去实现链表的数据结构。效果其他应该是一致的。

    AC code:

    #include <cstdio>
    #include <list>
    using namespace std;
     
    int main()
    {
      int n,k;
      while(scanf("%d%d",&n,&k)!=EOF)
      {
        if(n==0 && k==0)
          printf("NULL
    ");
        else
        {
          list<int> lst1,lst2,lst3;
          int tt;
          for(int i=0;i<n;++i)
          {
            scanf("%d",&tt);
            lst1.push_back(tt);
          }
          for(int i=0;i<k;++i)
          {
            scanf("%d",&tt);
            lst2.push_back(tt);
          }
          list<int>::iterator it1=lst1.begin(),it2=lst2.begin();
          while(it1!=lst1.end() || it2!=lst2.end())
          {
            if(it1==lst1.end())
              lst3.push_back(*it2++);
            else if(it2==lst2.end())
              lst3.push_back(*it1++);
            else
            {
              if(*it1<*it2)
                lst3.push_back(*it1++);
              else
                lst3.push_back(*it2++);
            }
          }
          for(list<int>::iterator it=lst3.begin();it!=lst3.end();++it)
          {
            if(it!=lst3.begin())
              printf(" ");
            printf("%d",*it);
          }
     
          printf("
    ");
        }
      }
      return 0;
    }
    /**************************************************************
        Problem: 1519
        User: huo_yao
        Language: C++
        Result: Accepted
        Time:280 ms
        Memory:1024 kb
    ****************************************************************/
    题目链接:http://ac.jobdu.com/problem.php?pid=1519

    九度-剑指Offer习题全套答案下载:http://download.csdn.net/detail/huoyaotl123/8276299



  • 相关阅读:
    POJ 1330 Nearest Common Ancestors(LCA Tarjan算法)
    LCA 最近公共祖先 (模板)
    线段树,最大值查询位置
    带权并查集
    转负二进制
    UVA 11437 Triangle Fun
    UVA 11488 Hyper Prefix Sets (字典树)
    UVALive 3295 Counting Triangles
    POJ 2752 Seek the Name, Seek the Fame (KMP)
    UVA 11584 Partitioning by Palindromes (字符串区间dp)
  • 原文地址:https://www.cnblogs.com/huoyao/p/4248904.html
Copyright © 2011-2022 走看看