您的位置:首页 > 其它

leetcode insertion-sort-list

2014-11-26 21:56 337 查看

单链表的插入排序

问题描述:

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 链表