合并两个有序链表(面试题 17)

  题目:输入两个递增的排序链表,合并者两个链表中的结点仍然是按照递增排序。

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


typedef struct Node{  
    int value;  
    struct Node* next;  
}Node;  




Node* create_list()  
{  
    int data;  
    Node* head =NULL,*cur;  
    cin>>data;  
    while (data !=-1)  
    {  
        Node* pNode =(Node*)malloc(sizeof(Node));  
        pNode->value =data;  
        pNode->next =NULL;  
        if (head==NULL)  
        {  
            head =pNode;  
            cur =pNode;  
        }  
        else  
        {  
            cur->next =pNode;  
            cur =cur->next;    
        }  
        cin>>data;  
    }  
    return head;  
}  




Node* mergelistRecursive(Node* list1,Node* list2)
{
	Node* result;
	if (!list1)
	{
		return list2;
	}
	if (!list2)
	{
		return list1;
	}


	if (list1->value>list2->value)
	{
		result =list2;
		result->next =mergelistRecursive(list1,list2->next);
	}
	if (list1->value<list2->value)
	{
		result =list1;
		result->next =mergelistRecursive(list1->next,list2);
	}	
	return result;
}


Node* mergerlistNonReursively(Node* head1,Node* head2)
{
	Node* result,*p1=head1,*p2=head2;
	if (!head1)
	{
		return head2;
	}
	if (!head2)
	{
		return head1;
	}


	if (p1->value>p2->value)
	{
		result =p2;
		p2 =p2->next;
	}
	else
	{
		result =p1;
		p1 =p1->next;
	}
	Node* head =result;
	while (p1&&p2)
	{
		if (p1->value>p2->value)
		{
			result->next =p2;
			p2 =p2->next;
			result =result->next;
		}
		else
		{
			result->next =p1;
			p1 =p1->next;
			result =result->next;
		}
	}
	
	if (p1)
	{
		result->next =p1;
	}


	if (p2)
	{
		result->next =p2;
	}
	return head;
}


void print(Node* head)  
{  
    Node* cur =head;  
    while(cur)  
    {  
        cout<<cur->value<<" ";  
        cur =cur->next;  
    }  
    cout<<endl;  
}  


void main()
{
	Node* list1,*list2,*list3;
	list1 =create_list();
	print(list1);	
	list2 =create_list();
	print(list2);
	//list3 =mergelistRecursive(list1,list2);
	list3 =mergerlistNonReursively(list1,list2);
	print(list3);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值