您的位置:首页 > 其它

LeetCode题解:Insertion Sort List

2013-11-14 01:37 337 查看

Insertion Sort List

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)
return nullptr;

ListNode* inserted = head;

while(inserted->next != nullptr)
{
// find the position of insertion
ListNode* i = head;

// is insertion on the head?
if (i->val >= inserted->next->val)
i = inserted->next->next,
inserted->next->next = head,
head = inserted->next,
inserted->next = i;
else
{
// make i locate at the node prior to the insertion
while(! (i->next->val >= inserted->next->val))
i = i->next;

if (i != inserted)
{
ListNode* tmp = inserted->next;
// insert
inserted->next = tmp->next;
tmp->next = i->next;
i->next = tmp;
}
else
inserted=inserted->next;
}
}

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