您的位置:首页 > 其它

LeetCode: Insertion Sort List

2014-08-07 15:35 302 查看
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 == NULL || head->next == NULL)
return head;
ListNode* cur = head->next;
ListNode* itr = head;
ListNode* pre = head;
itr->next = NULL;
while(cur)
{
itr = head;
ListNode* next = cur->next;
if(cur->val < itr->val)
{
cur->next = itr;
head = cur;
}
else
{

while(itr != NULL)
{
if(cur->val >= itr->val)
{
if(itr->next == NULL)
{
itr->next = cur;
cur->next = NULL;
break;
}
else
{
pre = itr;
itr = itr->next;
}
}
else
{
pre->next = cur;
cur->next = itr;
break;
}
}
}

cur = next;
}
return head;
}
};

Round 2:

class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
if(head == NULL || head->next == NULL)
return head;
ListNode *right = head->next;
head->next = NULL;
while(right != NULL)
{
ListNode *left = head;
ListNode *pre = NULL;
ListNode *next = right->next;
while(left != NULL && right->val > left->val)
{
pre = left;
left = left->next;
}
if(pre == NULL)
{
right->next = left;
head = right;
}
else
{
pre->next = right;
right->next = left;
}
right = next;
}
return head;
}
};


Round 3:

/**
* 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(NULL == head || NULL == head->next)
return head;
ListNode *right = head->next, *pre = NULL, *left = head;
head->next = NULL;
while(NULL != right)
{
ListNode *next = right->next;
if(right->val <= head->val)
{
right->next = head;
head = right;
}
else
{
ListNode *left = head;
while(NULL != left && right->val > left->val)
{
pre = left;
left = left->next;
}
if(left == NULL)
{
pre->next = right;
right->next = NULL;
}
else
{
pre->next = right;
right->next = left;
}
}
right = next;
}
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: