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);
}

結果:ios

數據爲:1數據爲:3數據爲:5數據爲:7數據爲:9
數據爲:2數據爲:4數據爲:6數據爲:8數據爲:10
數據爲:1數據爲:2數據爲:3數據爲:4數據爲:5數據爲:6數據爲:7數據爲:8數據爲:9數據爲:10
相關文章
相關標籤/搜索