LeetCode-Insertion Sort List
2014-07-28 16:11
411 查看
Sort a linked list using insertion sort.
Solution:
Code:
<span style="font-size:14px;">/**
* 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 == NULL || head->next == NULL) return head;
ListNode *begin = head, *nextNode, *before, *after;
head = head->next;
//attention
begin->next = NULL;
while (head != NULL) {
nextNode = head->next;
if (head->val <= begin->val) {
head->next = begin;
begin = head;
} else {
before = begin;
while (before->next != NULL && before->next->val < head->val)
before = before->next;
if (before->next == NULL) {
before->next = head;
head->next = NULL;
} else {
after = before->next;
before->next = head;
head->next = after;
}
}
head = nextNode;
}
return begin;
}
};</span>
Solution:
Code:
<span style="font-size:14px;">/**
* 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 == NULL || head->next == NULL) return head;
ListNode *begin = head, *nextNode, *before, *after;
head = head->next;
//attention
begin->next = NULL;
while (head != NULL) {
nextNode = head->next;
if (head->val <= begin->val) {
head->next = begin;
begin = head;
} else {
before = begin;
while (before->next != NULL && before->next->val < head->val)
before = before->next;
if (before->next == NULL) {
before->next = head;
head->next = NULL;
} else {
after = before->next;
before->next = head;
head->next = after;
}
}
head = nextNode;
}
return begin;
}
};</span>
相关文章推荐
- LeetCode题目5:Insertion Sort List
- Insertion Sort List 【leetcode】
- 【LeetCode】Insertion Sort List
- [leetcode] Insertion Sort List(python)
- ****(leetcode)Insertion Sort List
- leetcode---Insertion Sort List
- LeetCode——Insertion Sort List
- [LeetCode]Insertion Sort List
- Leetcode Insertion Sort List
- (leetcode)Insertion Sort List
- LeetCode Insertion Sort List
- [LeetCode]Insertion Sort List
- 【LeetCode】Insertion Sort List
- Leetcode:Insertion Sort List
- C实现 LeetCode->Insertion Sort List(排序)(单链表)
- Insertion Sort List (LeetCode)
- 【Leetcode】Insertion Sort List
- [LeetCode]Insertion Sort List
- [LeetCode] Insertion Sort List
- leetcode Insertion Sort List(*)