您的位置:首页 > 其它

[leetcode]Insertion Sort List

2013-12-26 14:01 435 查看
给一个链表,用插入排序...

就是考链表的基本操作...

开始想法很2,重新new一个链表...

但是我明明都有链表了,我去new干嘛呢...

其实嘛,排序就是把链表重新连下就好啦,一个一个的独立块,把next重新连下

要是不做这题我还真不会这么去做,平时链表用的太少了T_T

还有就是单向链表,要在当前位置插入东西的话要记录他的上一位置才行哟。。。

/**
* 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 head;

ListNode* curr = head -> next;
head -> next = nullptr;

while(curr != nullptr){
ListNode* tmpHead = head;
ListNode* prev = nullptr;
ListNode* next = curr -> next;
while(tmpHead != nullptr && tmpHead -> val <= curr -> val)
{
prev = tmpHead;
tmpHead = tmpHead -> next;
}

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