单链表的插入排序
问题描述:
Sort a linked list using insertion sort. https://oj.leetcode.com/problems/insertion-sort-list/点击打开链接
问题分析:
单链表的插入排序,插入排序是一个基本的排序方法,因为链表不能够随机访问所以与array的简单排序有所差别。为了方便操作采用重新构造表头的方案。
定义:
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
C代码:
ListNode *insertionSortList(ListNode *head)
{
if (!head || !head->next) /* 一个元素不需要排序 */
{
return head;
}
ListNode node(0), *hd = &node;
while (head)
{
ListNode *cur = head; /* 当前需要处理的节点 */
head = head->next; /* 下一个需要处理的节点 */
ListNode *h, *p = NULL;
for (h = node.next; h; h = h->next) /* 在已经排序的链表中查找位置 */
{
if (h->val < cur->val) p = h;
else break;
}
if (!p) /* 当前为最小元素, 没有找到位置 */
{
cur->next = hd->next; hd->next = cur;
}
else /* 找到位置 */
{
cur->next = p->next; p->next = cur;
}
}
return node.next;
}