Sort a linked list in O(n log n) time using constant space complexity.
2017-03-17 00:14
405 查看
/**
* 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;
}
};
相关文章推荐
- Sort a linked list in O(n log n) time using constant space complexity.
- leetcode_Sort a linked list in O(n log n) time using constant space complexity.
- leetcode Sort List (Sort a linked list in O(n log n) time using constant space complexity)
- leetcode Sort a linked list in O(n log n) time using constant space complexity.
- Sort a linked list in O(n log n) time using constant space complexity.
- Sort a linked list in O(n log n) time using constant space complexity.
- Sort a linked list in O(n log n) time using constant space complexity.
- Sort a linked list in O(n log n) time using constant space complexity
- Sort_list——Sort a linked list in O(n log n) time using constant space complexity. 合并排序
- Point-in-Time (Incremental) Recovery Using the Binary Log
- Sort a linked list using insertion sort
- Sort a linked list using insertion sort
- leetcode上的Sort a linked list using insertion sort
- 【Leetcode】Sort List in O(nlogn) O(1)space
- Reverse a doubly linked list in O(1) time
- Point-in-Time (Incremental) Recovery Using the Binary Log
- [LeetCode] 148. Sort List (Linked List) - Using Quick Sort(小改动)
- LeetCode234——Palindrome Linked List,O(n) time and O(1) space
- leetcode_Sort a linked list using insertion sort.
- bubble sort in linked list....(java version)