LeetCode 147. Insertion Sort List
Solution1:我的答案
有点笨,有点慢
/**
* 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) return NULL;
if (!head->next) return head;
ListNode* new_head = new ListNode(-1), *cur = head;
while (cur) {
ListNode *temp = cur->next;
cur->next = NULL;
my_insert(new_head, cur);
cur = temp;
}
return new_head->next;
}
void my_insert (ListNode* &new_head, ListNode* &des) {
if (!new_head->next || des->val <= new_head->next->val) {
ListNode *temp = new_head->next;
new_head->next = des;
des->next = temp;
return;
} else {
ListNode* cur = new_head->next;
while (cur->next) {
if (des->val >= cur->val && des->val <= cur->next->val) {
des->next = cur->next;
cur->next = des;
return;
}
else
cur = cur->next;
}
cur->next = des;
return;
}
}
};
Solution2:
参考网址:http://www.cnblogs.com/grandyang/p/4250107.html
/**
* 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) {
ListNode *dummy = new ListNode(-1), *cur = dummy;
while (head) {
ListNode *t = head->next;//暂时保存头结点的下一个位置
cur = dummy;
while (cur->next && cur->next->val <= head->val) {
cur = cur->next;
}
head->next = cur->next;
cur->next = head;
head = t;
}
return dummy->next;
}
};
要反思为啥别人的代码写的如此简洁~~~
本文提供了两种实现LeetCode 147题“插入排序链表”的解决方案。第一种方法较为直观但效率较低;第二种方法借鉴他人思路,代码更为简洁高效。通过对两种方法的对比,可以学习到如何优化链表操作。
283

被折叠的 条评论
为什么被折叠?



