147. Insertion Sort List
来源:互联网 发布:淘宝泳装模特 编辑:程序博客网 时间:2024/03/28 21:33
题目:
Sort a linked list using insertion sort.
题意:
使用插入排序排列链表
思路:
按照插入排序的算法,对链表进行轮询,将当前链表节点值与链表之前的部分进行对比,找到合适的位置进行插入。
代码:24ms
/** * 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) return head; ListNode *dummy = new ListNode(-1); ListNode *cur = head; ListNode *prev = dummy; ListNode *next = NULL; while(cur){ next = cur->next; if(!prev || !prev->next || prev->next->val>=cur->val) prev = dummy; while(prev->next && prev->next->val<cur->val){ prev = prev->next; //跳过小于当前节点值的部分 } cur->next = prev->next; //插入当前节点 prev->next = cur; cur = next; } return dummy->next; }};代码:88ms
/** * 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) return head; ListNode dummy(-1); while(head){ ListNode *iter = &dummy; while(iter->next && iter->next->val < head->val){ iter = iter->next; } ListNode *next = head->next; head->next = iter->next; iter->next = head; head = next; } return dummy.next; }};
0 0
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 147. Insertion Sort List
- 剑指Offer----面试题29:扩展----数组中第K小的数字
- 聊聊Linux动态链接中的PLT和GOT(2)——延迟重定位
- lua基础(一)
- acm之搜索题目4
- STL容器之优先队列
- 147. Insertion Sort List
- poj 3176 Cow Bowling
- 阿里大数据技术
- java(3)------运算符常用大全
- Mysql日志文件
- JSTL标签不起作用,JSTL标签直接输出表达式
- mysql中MAX()函数MIN()函数
- Nor Flash & Nand Flash & OneNand Flash
- 自己在Web前端项目中解决bug的思路