/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
static bool sort_by_value(const int &a,const int &b)
{
return a<b;
}
ListNode *sortList(ListNode *head)
{
vector<int> res;
if(head == NULL)
return head;
ListNode *temp = head;
while(temp != NULL)
{
res.push_back(temp->val);
temp = temp->next;
}
sort(res.begin(),res.end());
//sort(res.begin(),res.end().sort_by_value);
temp = head;
vector<int>::iterator iter = res.begin();
while(temp != NULL)
{
temp->val = *iter;
iter++;
temp = temp->next;
}
return head;
}
};
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
static bool sort_by_value(const int &a,const int &b)
{
return a<b;
}
ListNode *sortList(ListNode *head)
{
vector<int> res;
if(head == NULL)
return head;
ListNode *temp = head;
while(temp != NULL)
{
res.push_back(temp->val);
temp = temp->next;
}
sort(res.begin(),res.end());
//sort(res.begin(),res.end().sort_by_value);
temp = head;
vector<int>::iterator iter = res.begin();
while(temp != NULL)
{
temp->val = *iter;
iter++;
temp = temp->next;
}
return head;
}
};
本文介绍了一种使用C++实现的链表排序算法。通过将链表元素存储到一个临时数组中,然后对数组进行排序,最后再将排序后的值重新赋给链表节点的方式实现了链表的升序排列。
2325

被折叠的 条评论
为什么被折叠?



