LeetCode(147) Insertion Sort List
来源:互联网 发布:军事题材的网络电影 编辑:程序博客网 时间:2024/06/03 22:59
题目
Sort a linked list using insertion sort.
分析
实现链表的插入排序
注意:
- 程序入口的特殊输入判断处理!
- 节点的链接处理,避免出现断链!
AC代码
/** * 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) return head; ListNode *p = head->next; head->next = NULL; //从头结点的下一节点开始,遍历插入排序 while (p) { //保存p节点的后续节点 ListNode *r = p->next; //判断是否应插入到头结点 if (p->val < head->val) { p->next = head; head = p; } else{ //寻找p节点应插入位置的前驱 ListNode *pre = head; while (pre->next && pre->next->val <= p->val) { pre = pre->next; } p->next = pre->next; pre->next = p; } //循环下一节点的插入 p = r; }//while return head; }};
GitHub测试程序源码
0 0
- LeetCode(147) Insertion Sort List
- LeetCode 147 Insertion Sort List(链表)
- LeetCode(147) Insertion Sort List
- LeetCode: Insertion Sort List [147]
- LeetCode 147 Insertion Sort List
- [leetcode 147] Insertion Sort List
- LeetCode 147 Insertion Sort List
- LeetCode 147 Insertion Sort List
- [leetcode 147]Insertion Sort List
- leetcode-147 Insertion Sort List
- [LeetCode 147]Insertion Sort List
- Leetcode[147]-Insertion Sort List
- Insertion Sort List - LeetCode 147
- leetcode[147]:Insertion Sort List
- LeetCode(147) Insertion Sort List
- leetcode 147: Insertion Sort List
- [Leetcode]#147 Insertion Sort List
- leetCode #147 Insertion Sort List
- 设计无形
- OC基础第四章:@property和@synthesize
- 8205A
- UBIFS根文件系统制作及移植
- windows和linux下简单的软件级调整相机曝光时间(或其他参数)的方式
- LeetCode(147) Insertion Sort List
- Maven和Ant的区别
- [leetcode297]Serialize and Deserialize Binary Tree
- Java内部类的调用
- java面试:兔子问题
- hdoj 1269 迷宫城堡
- tnsnames.ora中UR=A配置使用
- 南阳理工 括号配对题解
- 【ACM】1020:迭代法