天天看點

請編寫一段代碼,實作兩個單向有序連結清單的合并

#include <iostream>
#include <malloc.h>
#include <vector>
using namespace std;
typedef struct Node
{
    int data;
    struct Node* next;
    
}LNode,*Linklist;

void PrintList(Linklist head)
{
	Linklist tmp=head;
	while(tmp!=NULL)
	{
	
		
		cout<<tmp->data<<" ";
        tmp=tmp->next;
		
	 } 
} 
Linklist CreatList(Linklist head)
{
	head=(Linklist)malloc(sizeof(struct Node));
	LNode* node=NULL;
	LNode* end=NULL;
	int num;
    vector<int> vec;
	head->next=NULL;
	end=head;	
	while(cin>>num){
		vec.push_back(num);
		if(cin.get()=='\n')
		break;
        
        }
    
    for(int i=0;i<vec.size();i++){
        node=(Linklist)malloc(sizeof(struct Node));
		node->data=vec[i];
		end->next=node;
		end=node;        

    }
	end->next=NULL; 
	return head;
}
Linklist MergeList(Linklist head1,Linklist head2)
{
   Linklist mergeHead=(Linklist)malloc(sizeof(struct Node));
    if(head1==NULL)
        return head2;
    else if(head2==NULL)
        return head1;
    if(head1->data<head2->data)
    {
        mergeHead=head1;
        mergeHead->next=MergeList(head1->next,head2);
       
    }
    else if (head1->data>=head2->data)
    {
        mergeHead=head2;
        mergeHead->next=MergeList(head1,head2->next);
       
    }
    return mergeHead;
}

int main()
{
  Linklist head1,head2,head3=NULL;
  head1=CreatList(head1);
  head2=CreatList(head2);
  head3=MergeList(head1->next,head2->next);
  PrintList(head3);
  
  return 0;
}
           

繼續閱讀