[leetcode]147. Insertion Sort List
2017-07-25 18:02
363 查看
题目链接:https://leetcode.com/problems/insertion-sort-list/#/description
Sort a linked list using insertion sort.class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
ListNode* new_head = new ListNode(0);
new_head -> next = head;
ListNode* pre = new_head;
ListNode* cur = head;
while (cur) {
if (cur -> next && cur -> next -> val < cur -> val) {
while (pre -> next && pre -> next -> val < cur -> next -> val)
pre = pre -> next;
/* Insert cur -> next after pre.*/
ListNode* temp = pre -> next;
pre -> next = cur -> next;
cur -> next = cur -> next -> next;
pre -> next -> next = temp;
/* Move pre back to new_head. */
pre = new_head;
}
else cur = cur -> next;
}
ListNode* res = new_head -> next;
delete new_head;
return res;
}
};
Sort a linked list using insertion sort.class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
ListNode* new_head = new ListNode(0);
new_head -> next = head;
ListNode* pre = new_head;
ListNode* cur = head;
while (cur) {
if (cur -> next && cur -> next -> val < cur -> val) {
while (pre -> next && pre -> next -> val < cur -> next -> val)
pre = pre -> next;
/* Insert cur -> next after pre.*/
ListNode* temp = pre -> next;
pre -> next = cur -> next;
cur -> next = cur -> next -> next;
pre -> next -> next = temp;
/* Move pre back to new_head. */
pre = new_head;
}
else cur = cur -> next;
}
ListNode* res = new_head -> next;
delete new_head;
return res;
}
};
相关文章推荐
- leetcode 147. Insertion Sort List (Python版)
- Leetcode 147. Insertion Sort List(链表实现快排)
- Leetcode-147. Insertion Sort List
- leetcode 147. Insertion Sort List
- LeetCode 147. Insertion Sort List
- [leetcode] 【排序】 147. Insertion Sort List
- leetcode之147. Insertion Sort List(C++解法)
- Leetcode: 147. Insertion Sort List
- LeetCode 147. Insertion Sort List
- [LeetCode]147. Insertion Sort List 深入浅出讲解和代码示例
- Leetcode——147. Insertion Sort List
- [leetcode] 147. Insertion Sort List 解题报告
- leetcode题解-147. Insertion Sort List
- LeetCode 147. Insertion Sort List(插入有序链表)
- LeetCode 147. Insertion Sort List
- [LeetCode]147. Insertion Sort List
- [LeetCode] 147. Insertion Sort List
- LeetCode#147. Insertion Sort List
- [LeetCode] 147. Insertion Sort List
- leetcode147. Insertion Sort List