[Leetcode] 147. Insertion Sort List 解题报告
来源:互联网 发布:网络爬虫 编辑:程序博客网 时间:2024/05/22 00:44
题目:
Sort a linked list using insertion sort.
思路:
插入排序很经典,所以在链表中实现插入排序是锻炼基本功的一道好题目。基本思路就是:首先将原始的链表断链成为两部分,第一部分仅包含head,代表已经排好序的链表;第二部分包含其余结点,代表尚未排序的链表。然后每次取出未排序链表的头部,线性扫描排好序的链表,并将其插入适当的位置;循环这个过程,直到未排序的链表变为空。算法的时间复杂度是O(n^2),空间复杂度是O(1)。还记得虚拟头结点吗?它可以使得对链表的特殊情况的处理大大简化。
代码:
/** * 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 *pre_head = new ListNode(0); pre_head->next = head; ListNode *node = head->next; head->next = NULL; while (node != NULL) { ListNode *next_node = node->next; // record the next node ListNode *pre_node = pre_head; while (pre_node->next && pre_node->next->val < node->val) { pre_node = pre_node->next; } node->next = pre_node->next; pre_node->next = node; node = next_node; } head = pre_head->next; delete pre_head; return head; }};
0 0
- [leetcode] 147. Insertion Sort List 解题报告
- [Leetcode] 147. Insertion Sort List 解题报告
- LeetCode—Insertion Sort List 解题报告
- Leetcode Insertion Sort List 解题报告
- leetCode解题报告之Insertion Sort List
- Leetcode Insertion Sort List 解题报告
- [LeetCode OJ] Insertion Sort List 解题报告
- 【LeetCode】Insertion Sort List 解题报告
- 景岁的Leetcode解题报告:147.Insertion Sort List (Java)
- [LeetCode]Sort List,解题报告
- LeetCode Sort List 解题报告
- Leetcode Sort List 解题报告
- LeetCode 解题报告 Sort List
- LeetCode Sort List 解题报告
- LeetCode 147. Insertion Sort List
- [LeetCode]147.Insertion Sort List
- [leetcode] 147.Insertion Sort List
- 147. Insertion Sort List LeetCode
- java 远程方法调用示例
- 实体类含有自身或者另一个实体时转json
- Leetcode 404(Java)
- 性能分析之IO分析-jbd2引起的IO高
- Python 小案例 打字练习
- [Leetcode] 147. Insertion Sort List 解题报告
- IP地址最后一位斜杠是什么意思?比如192.168.1.10/27?还有IP地址和子网掩码相加得到的网络地址是什么意思
- Hibernate多对多
- 需求变更,产品经理的良心也会痛!
- BZOJ 3831: [Poi2014]Little Bird
- 十分钟入门Matplotlib
- HCA卡的MTU仅仅对IPOIB有效,对RDMA没有速度提升.
- 一段ping延迟监控引发的调查
- Java.Util.concurrent包学习