您的位置:首页 > 其它

[Leetcode]#147 Insertion Sort List

2015-09-02 07:45 302 查看
//#147 Insertion Sort List
//80ms 81.07%
#include <iostream>
using namespace std;

/**
* 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)
//"insertion sort"
{
if(head == NULL || head->next == NULL) return head;
//after this point, all in coming linked lists have a size of 2 or more

ListNode *p, *next_p, *n;
//ListNode *end,
//end = head;
p = head->next;
next_p = p->next;

head->next = NULL;
//end->next = NULL;

while(p != NULL)
{
//cout << "L0 ";
p->next = NULL;

if(head->val > p->val)
{
p->next = head;
head = p;
}
else
{
n = head;
while(n->next != NULL)
{
//cout << "L1 ";
if(n->next->val > p->val)
{
p->next = n->next;
n->next = p;
break;
}
n = n->next;
}
n->next = p;
}
//insertion finished
//prepare for next item

p = next_p;
if(next_p != NULL)
{
next_p = next_p->next;
}

//list_print(head);
}

return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode linkedlist