# LeetCode | 147. Insertion Sort List

Sort a linked list using insertion sort.

A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.
With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list

Algorithm of Insertion Sort:

1. Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
3. It repeats until no input elements remain.

Example 1:

Input: 4->2->1->3
Output: 1->2->3->4


Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5

/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
while(p != NULL)
{
cur = p;
p = p->next;
{
cur->next = NULL;
}
else
{
ListNode *pre = NULL;
for(q = new_head; q != NULL; q = q->next)
{
if(cur->val < q->val)
{
if(pre == NULL)
{
cur->next = q;
}
else
{
pre->next = cur;
cur->next = q;
}
break;
}
pre = q;
}
if(q == NULL)
{
pre->next = cur;
cur->next = NULL;
}
}
}
}
};

P.S. 感谢遇到了成交cp，真的又暖又甜~ 也许不管在什么时候，美好的事物都是那么美好吧~ 加油呀~

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

1LOVESJohnny

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文

10-29 436
06-09 3285
01-07 389
06-30 237