The Solution to LeetCode 147 Insertion Sort List
2017-02-26 17:50
579 查看
Question:
Sort a linked list using insertion sort.
思路:本题采用直接插入排序。
Answer:
/**
* 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)
{
return NULL;
}
else
{
ListNode* q = head->next;
head->next = NULL;
while(q!=NULL)
{
ListNode* p = head;
if(q->val < p->val)
{
head = q;
q=q->next;
head->next=p;
}
else
{
while(p!=NULL)
{
if(p->next ==NULL)
{
p->next =q;
q=q->next;
p->next->next = NULL;
break;
}
else
{
if(q->val < p->next->val)
{
ListNode* tmp = p->next;
p->next = q;
q=q->next;
p->next->next = tmp;
break;
}
p=p->next;
}
}
}
}
return head;
}
}
};
Run code results:
Your input
[3 2 3 6 1 8 3 0 4 2 5 6 1 13 9 15]
Your answer
[0,1,1,2,2,3,3,3,4,5,6,6,8,9,13,15]
Expected answer
[0,1,1,2,2,3,3,3,4,5,6,6,8,9,13,15]
Sort a linked list using insertion sort.
思路:本题采用直接插入排序。
Answer:
/**
* 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)
{
return NULL;
}
else
{
ListNode* q = head->next;
head->next = NULL;
while(q!=NULL)
{
ListNode* p = head;
if(q->val < p->val)
{
head = q;
q=q->next;
head->next=p;
}
else
{
while(p!=NULL)
{
if(p->next ==NULL)
{
p->next =q;
q=q->next;
p->next->next = NULL;
break;
}
else
{
if(q->val < p->next->val)
{
ListNode* tmp = p->next;
p->next = q;
q=q->next;
p->next->next = tmp;
break;
}
p=p->next;
}
}
}
}
return head;
}
}
};
Run code results:
Your input
[3 2 3 6 1 8 3 0 4 2 5 6 1 13 9 15]
Your answer
[0,1,1,2,2,3,3,3,4,5,6,6,8,9,13,15]
Expected answer
[0,1,1,2,2,3,3,3,4,5,6,6,8,9,13,15]
相关文章推荐
- LeetCode 147 Insertion Sort List
- leetcode_147题——Insertion Sort List(线性表,插入排序)
- leetCode #147 Insertion Sort List
- LeetCode 147 — Insertion Sort List(C++ Java Python)
- Java for LeetCode 147 Insertion Sort List
- [Leetcode 147, medium] Insertion Sort List
- LeetCode147_Insertion Sort List(用插入排序算法对链表进行排序) Java题解
- LeetCode(147) Insertion Sort List
- leetcode 147 —— Insertion Sort List
- leetcode 147: Insertion Sort List
- LeetCode: Insertion Sort List [147]
- [LeetCode]147 Insertion Sort List
- 【leetcode】【单链表】【147】Insertion Sort List
- Leetcode[147]-Insertion Sort List
- 【LeetCode-面试算法经典-Java实现】【147-Insertion Sort List(链表插入排序)】
- [LeetCode 147] Insertion Sort List
- LeetCode147: Insertion Sort List
- [Leetcode Solution]Insertion Sort List
- LeetCode(147) Insertion Sort List
- LeetCode(147) Insertion Sort List