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 with Python】 Insertion Sort List
- [leetcode] Insertion Sort List
- [LeetCode]147 Insertion Sort List
- leetcode_Insertion Sort List
- [LeetCode]Insertion Sort List
- LEETCODE: Insertion Sort List
- LeetCode 147 Insertion Sort List
- Leetcode: Insertion Sort List
- Insertion Sort List —— LeetCode
- [Leetcode 147, medium] Insertion Sort List
- LeetCode: Insertion Sort List
- 【leetcode】Insertion Sort List
- leetcode之insertion Sort list
- [LeetCode] Insertion Sort List 链表插入排序
- Insertion Sort List -- leetcode
- [LeetCode] Insertion Sort List
- LeetCode: Insertion Sort List [147]
- LeetCode OJ Insertion Sort List
- [leetcode] Insertion Sort List(python)
- LeetCode-Insertion Sort List