一、题目
描述
给定一个无序单链表,实现单链表的排序(按升序排序)。
示例1
输入:
[1,3,2,4,5]
返回值:
{1,2,3,4,5}
二、思路
1、将链表的数添加到vector容器中,再将vector中的数sort排序,最后将vector容器中的数据重新添加回原链表
三、代码
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类 the head node
* @return ListNode类
*/
ListNode* sortInList(ListNode* head) {
vector<int>res;
ListNode* node=head;
ListNode* p=head;
while(node)
{
res.emplace_back(node->val);
node=node->next;
}
sort(res.begin(),res.end());
int pos=0;
while(p)
{
p->val=res[pos++];
p=p->next;
}
return head;
}
};