LeetCode题解:Insertion Sort List
2013-11-14 01:37
337 查看
Insertion Sort List
Sort a linked list using insertion sort.思路:
标准的插入排序。就是考察一下链表的操作而已。
题解:
/** * 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 == nullptr) return nullptr; ListNode* inserted = head; while(inserted->next != nullptr) { // find the position of insertion ListNode* i = head; // is insertion on the head? if (i->val >= inserted->next->val) i = inserted->next->next, inserted->next->next = head, head = inserted->next, inserted->next = i; else { // make i locate at the node prior to the insertion while(! (i->next->val >= inserted->next->val)) i = i->next; if (i != inserted) { ListNode* tmp = inserted->next; // insert inserted->next = tmp->next; tmp->next = i->next; i->next = tmp; } else inserted=inserted->next; } } return head; } };
相关文章推荐
- Java 单例模式探讨
- 函数栈及缓冲区溢出攻击(一)
- JAVA 工厂模式简单例子
- linux下使用adb连接android手机
- 详解WPF Blend工具中的复合路径功能 ( 含路径标记语法 )
- Win7中隐藏的上帝模式——GodMode
- java 简单的单例模式 例子
- Android 4.4 Kitkat 编译时对于存储器挂载方式的修改,以泛泰820,860为例
- [未解决]数据库异常:多步 OLE DB 操作产生错误。如果可能,请检查每个 OLE DB 状态值。
- window API一天一练之邮槽
- wamp5如何配置多个自定义域名访问本地不同的项目
- Fedora 18/19没有注销
- C# 中有关 using 关键字
- 【数据挖掘概念与技术】学习笔记5-数据立方体技术
- Find M Integers from an Array of Size N equally
- svg图形
- C#中IPAddress和IPEndPoint的关系
- HDR照片算法去抖动
- 根据用户需求分析同行提升网站关键词排名
- 将博客搬至CSDN