zoukankan      html  css  js  c++  java
  • C++实现合并两个已经排序的链表

    /*
     * 合并两个已经排序的链表.cpp
     *
     *  Created on: 2018年4月11日
     *      Author: soyo
     */
    #include<iostream>
    using namespace std;
    struct Node{
        int num;
        Node * next;
    };
    Node * creat(int x)
    {
        Node *head;
        Node *p;
        head=new Node;
        p=head;
        p->num=x;
        p->next=NULL;
       return head;
    }
    Node * insert(Node*head,int data)
    {
        Node *p1,*p;
        p1=new Node;
        p1->num=data;
        p1->next=NULL;
         p=head;
         while(p->next!=NULL)
         {
             p=p->next;
         }
         p->next=p1;
         return head;
    }
    void printl(Node *head)
    {
          Node *p=head;
          while(p!=NULL)
          {
              cout<<"数据为:"<<p->num;
              p=p->next;
          }
          cout<<endl;
    }
    Node *Merge(Node*head1,Node*head2)
    {
        if(head1==NULL)
            return head2;
        else if(head2==NULL)
            return head1;
        Node *newHead=NULL;
        if(head1->num<head2->num)
        {
            newHead=head1;
            newHead->next=Merge(head1->next,head2);
        }
        else
        {
            newHead=head2;
            newHead->next=Merge(head1,head2->next);
        }
        return newHead;
    }
    
    int main()
    {
         Node *head=creat(1);
          // cout<<head->num<<endl;
           int i;
           int a[]={3,5,7,9};
           for(i=0;i<sizeof(a)/sizeof(int);i++)
           {
               head=insert(head,a[i]);
           }
           printl(head);
           Node *head2=creat(2);
            int b[]={4,6,8,10};
           for(i=0;i<sizeof(a)/sizeof(int);i++)
           {
               head2=insert(head2,b[i]);
           }
           printl(head2);
           Node *newMergeHead;
           newMergeHead=Merge(head,head2);
           printl(newMergeHead);
    }

    结果:

    数据为:1数据为:3数据为:5数据为:7数据为:9
    数据为:2数据为:4数据为:6数据为:8数据为:10
    数据为:1数据为:2数据为:3数据为:4数据为:5数据为:6数据为:7数据为:8数据为:9数据为:10
  • 相关阅读:
    SCOI2003 字符串折叠
    UVA1629 Cake slicing
    POI2008 KLO-Building blocks
    NOI导刊2010提高 符文之语
    MongoDB数据库的基本操作
    React Naive 解决防止多次点击的解决方法
    如何自定义修改博客园样式
    语法对照表ES5VSES6
    MongoDB数据库安装
    小程序学习2 常用小程序概念以及代码实现
  • 原文地址:https://www.cnblogs.com/soyo/p/8796192.html
Copyright © 2011-2022 走看看