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;
}