LeetCode 147. Insertion Sort List
2016-12-30 12:42
357 查看
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) {
ListNode dummy(0);
while (head != NULL) {
ListNode *pre = &dummy;
ListNode *cur = head;
head = head->next;
while ((pre->next != NULL) && (pre->next->val <= cur->val)) {
pre = pre->next;
}
if (pre->next == NULL) {
pre->next = cur;
cur->next = NULL;
}
else {
cur->next = pre->next;
pre->next = cur;
}
}
return dummy.next;
}
};
/**
* 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(0);
while (head != NULL) {
ListNode *pre = &dummy;
ListNode *cur = head;
head = head->next;
while ((pre->next != NULL) && (pre->next->val <= cur->val)) {
pre = pre->next;
}
if (pre->next == NULL) {
pre->next = cur;
cur->next = NULL;
}
else {
cur->next = pre->next;
pre->next = cur;
}
}
return dummy.next;
}
};
相关文章推荐
- [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 (JAVA)链表插入排序
- 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
- Leetcode ☞ 147. Insertion Sort List ☆
- [LeetCode]147. Insertion Sort List
- [LeetCode]147. Insertion Sort List
- leetcode 147. Insertion Sort List (Python版)
- 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 (Medium) (cpp)