递归合并两链表:LinkList:Merge Two Lists using recursive method

来源:互联网 发布:知乎4.3 编辑:程序博客网 时间:2024/04/29 13:49

// LinkList.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream"
using namespace std;

typedef struct _node
{
 int val;
 struct _node* next;

}Node;

 Node* MergeTwo(Node* h1,Node* h2)
 {
   Node *h,*a,*b;
   h=new Node();
   Node* pre=h;
   a=h1;
   b=h2;
  if(a&&b)
   {
    if(a->val>b->val)
    {
    pre->next=a;
    pre=pre->next;
    pre->next=MergeTwo(a->next,b);
    }
    else
    {
    pre->next=b;
    pre=pre->next;
    pre->next=MergeTwo(a,b->next);
    }
   }
   if(!a)
   pre->next=b;
   if(!b)
    pre->next=a;
   return h->next;
 }
int _tmain(int argc, _TCHAR* argv[])
{
 int m=4;
  Node* head=(Node*)malloc(sizeof(Node));
   head->val=0;
   head->next=NULL;
   for(int i=1;i<=4;i++)
   { 
    Node* n=(Node*)malloc(sizeof(Node));
   n->val=i;
   n->next=head;
   head=n;
   }
  
   Node* head2=new Node();
   head2->val=10;
   head2->next=NULL;
   Node* p2=head2;
    for(int i=9;i>4;i--)
   { 
    Node* n=(Node*)malloc(sizeof(Node));
   n->val=i;
   n->next=NULL;
   p2->next=n;
   p2=p2->next;
   }
   Node *tmp=MergeTwo(head,head2);
   while(tmp)
   {
    cout<<tmp->val<<" ";
    tmp=tmp->next;
   }
  
   cin.get();
 return 0;
}

 

原创粉丝点击