20170912_归并两个已经排好序的单链表

20170912_归并两个已经排好序的单链表


//21. Merge Two Sorted Lists 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

#include<iostream>
#include<vector>
using namespace std;

struct ListNode
{
	int val;
	ListNode *next;
	ListNode(int x):val(x),next(nullptr) {}
};

ListNode *CreatList(ListNode * &root, vector<int> &a)
{
	int n=a.size();
	if(n==0)
		return root=nullptr;
	else
	{
		root=new ListNode(a[0]);
		ListNode *r=root;
		for(int i=1; i<n; ++i)
		{
			ListNode *s=new ListNode(a[i]) ;
			r->next=s;
			r=s;
		}
		return root;
	}
}

void OutList(ListNode *root)
{
	ListNode *p=root;
	if(p==nullptr)
		return;
	else
	{
		while(p != nullptr)
		{
			if(p->next != nullptr)
				cout<<p->val<<",";
			else
				cout<<p->val;
			p=p->next;
		}
		cout<<endl;
	}
}

class Solution
{
public:
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)
	{
        ListNode *root=merge(l1,l2);
		return root;
    }
	//对两个有序的的单链表进行 一次归并
	ListNode *merge(ListNode *head1, ListNode *head2)
	{
		ListNode *temp=new ListNode(0);
		ListNode *p=temp;
		while(head1 != nullptr && head2 != nullptr)
		{
			if(head1->val <= head2->val)
			{
				p->next=head1;
				head1=head1->next;
			}
			else
			{
				p->next=head2;
				head2=head2->next;
			}
			p=p->next;
		}
		if(head1 != nullptr)
			p->next=head1;
		if(head2 != nullptr)
			p->next=head2;
		p=temp->next;
		temp->next=nullptr;
		delete temp;
		return p;
	}
};

int main()
{
	vector<int> a1,a2;
	int ch;
	cout<<"按照顺序输入单链表1节点数据:"<<endl;
	while(cin>>ch)
		a1.push_back(ch);
	cin.clear();
	cin.sync();//清楚缓冲
	ListNode *r;
	ListNode *root1=CreatList(r,a1);
	cout<<"单链表1建立完成."<<endl;
	cout<<"顺序输出单链表1:"<<endl;
	OutList(root1);
	cout<<"顺序输出单链表1完成."<<endl;

	cout<<"按照顺序输入单链表2节点数据:"<<endl;
	//cin.clear();
	while(cin>>ch)
		a2.push_back(ch);
	ListNode *root2=CreatList(r,a2);
	cout<<"单链表2建立完成."<<endl;
	cout<<"顺序输出单链表2:"<<endl;
	OutList(root2);
	cout<<"顺序输出单链表2完成."<<endl;

	//cout<<"逆置该单链表:"<<endl;
	//ListNode *root2=ConvertList(root);
	//cout<<"输出逆置后的单链表:"<<endl;
	//OutList(root2);
	//cout<<"逆置后的单链表输出完成."<<endl;

	Solution example;
	ListNode *root=example.mergeTwoLists(root1,root2);
	OutList(root);

	system("pause");
	return 0;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值