[LeetCode 148] Insertion Sort List
2014-08-16 04:50
337 查看
Sort a linked list using insertion sort.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
if(head == nullptr || head->next == nullptr) return head;
ListNode *min = head;
ListNode *max = head;
ListNode *cur = max->next;
while(cur != nullptr)
{
if(min->val >= cur->val)
{
min = cur;
cur = cur->next;
min->next = head;
head = min;
max->next = nullptr;
}
else if(max-> val <= cur -> val)
{
max->next = cur;
cur = cur->next;
max = max->next;
max->next = nullptr;
}
else
{
ListNode *mid = min->next;
ListNode *left = min;
ListNode *p = cur;
while(mid!= nullptr)
{
if(mid->val > cur->val)
{
p = p->next;
left->next = cur;
cur->next = mid;
cur = p;
mid = nullptr; //Stop the loop
}
else if(mid->val <= cur->val)
{
left = mid;
mid = mid->next;
}
}
}
}
return head;
}
};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
if(head == nullptr || head->next == nullptr) return head;
ListNode *min = head;
ListNode *max = head;
ListNode *cur = max->next;
while(cur != nullptr)
{
if(min->val >= cur->val)
{
min = cur;
cur = cur->next;
min->next = head;
head = min;
max->next = nullptr;
}
else if(max-> val <= cur -> val)
{
max->next = cur;
cur = cur->next;
max = max->next;
max->next = nullptr;
}
else
{
ListNode *mid = min->next;
ListNode *left = min;
ListNode *p = cur;
while(mid!= nullptr)
{
if(mid->val > cur->val)
{
p = p->next;
left->next = cur;
cur->next = mid;
cur = p;
mid = nullptr; //Stop the loop
}
else if(mid->val <= cur->val)
{
left = mid;
mid = mid->next;
}
}
}
}
return head;
}
};
相关文章推荐
- leetcode - Insertion Sort List
- Insertion Sort List | leetcode
- Leetcode: Insertion Sort List
- leetcode -- Insertion Sort List
- LeetCode Insertion Sort List
- leetCode刷题归纳-List(148 Sort List)
- leetcode之Insertion Sort List
- LeetCode:Insertion Sort List
- LeetCode147—Insertion Sort List
- leetcode 147 Insertion Sort List java 算法
- 【LEETCODE】147- Insertion Sort List [Python]
- LeetCode--Insertion Sort List
- LeetCode: Insertion Sort List
- [LeetCode] Insertion Sort List
- 【leetcode】【单链表】【147】Insertion Sort List
- LeetCode-Insertion Sort List-链表插入排序-链表操作
- LeetCode Insertion Sort List
- Leetcode: Insertion Sort List
- 【LeetCode-面试算法经典-Java实现】【147-Insertion Sort List(链表插入排序)】
- [LeetCode] Insertion Sort List