Leetcode 147. Insertion Sort List
题目:
Sort a linked list using insertion sort.
思路:
使用一个指针p指向未排好序的链表的第一个结点,在排序好的部分中找到找第一个大于等于q的前驱结点,将p对应的结点插入到正确位置,p重新指向未排好序的链表的第一个结点。直到链表完成排序好。
代码实现
代码:
/**
* 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 *p = head->next;
head->next = NULL;
while (p != NULL)
{
ListNode *pNext = p->next; /*store the next node to be insert*/
ListNode *q = head;
if (p->val < q->val) /*node p should be the new head*/
{
p->next = q;
head = p;
}
else
{
while (q != NULL && q->next != NULL && q->next->val <= p->val)
q = q->next;
p->next = q->next;
q->next = p;
}
p = pNext;
}
return head;
}
};