20170515_单链表的一种新颖排序算法—借助list容器

20170515_单链表的一种新颖排序算法—借助list容器



//147. Insertion Sort List 
//Sort a linked list using insertion sort.
//148. 是Sort List,使用的是归并排序法。
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
#include<iostream>
#include<vector>
#include<list>
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 *p=root;
		for(int i=1; i<n; ++i)
		{
			ListNode *r=new ListNode(a[i]);
			p->next=r;
			p=r;
		}
		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<<endl;
			p=p->next;
		}
	}
}

class Solution
{
public:
    ListNode *insertionSortList(ListNode *head)
	{
        ListNode *root=head;
		if(root == nullptr || root->next == nullptr)
			return root;
		else
		{
			list<int> ilist;
			for(ListNode *p=root; p!=nullptr; p=p->next)
				ilist.push_back(p->val);
			ilist.sort();	//升序排列
			for(ListNode *p=root; p!=nullptr; p=p->next)
			{
				p->val=ilist.front();	//	取出list的第一个元素放入单链表中
				ilist.pop_front();	//删除list 中的第一个元素
			}
			return root;
		}
    }
};

int main()
{
	vector<int> a;
	int ch;
	cout<<"依次输入单链表节点数据:"<<endl;
	while(cin>>ch)
		a.push_back(ch);
	cin.clear();
	cin.sync();
	ListNode *r;
	ListNode *root=CreatList(r,a);
	cout<<"单链表建立完成."<<endl;
	cout<<"顺序输出单链表:"<<endl;
	OutList(root);
	cout<<"顺序输出单链表完成."<<endl<<endl;

	Solution example;
	ListNode *result;
	result=example.insertionSortList(root);
	OutList(root);
	cout<<"顺序输出单链表完成."<<endl<<endl;
	
	system("pause");
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值