Insertion Sort List
2015-08-09 11:52
204 查看
问题描述
Sort a linked list using insertion sort.
解决思路
1. 设置first和last指针;
2. 插入分三种情况。
程序
Sort a linked list using insertion sort.
解决思路
1. 设置first和last指针;
2. 插入分三种情况。
程序
public class Solution { public ListNode insertionSortList(ListNode head) { ListNode dummy = new ListNode(-1); ListNode first = null, last = null; ListNode cur = head; while (cur != null) { ListNode next = cur.next; // save the next node cur.next = null; if (first == null || last == null) { dummy.next = cur; first = cur; last = cur; } else { if (cur.val <= first.val) { // insert before the first dummy.next = cur; cur.next = first; first = cur; } else if (cur.val >= last.val) { // insert after last last.next = cur; last = cur; } else { // find the insert place ListNode node = first; while (node.next != null) { if (node.next.val > cur.val) { break; } node = node.next; } ListNode tmp = node.next; node.next = cur; cur.next = tmp; } } cur = next; } return first; } }
相关文章推荐
- 2015自考数据结构导论——宏观篇
- Android AIDL线程通信之Service回调客户端Activity
- 1083. List Grades (25)
- 2015年第二学期的计划
- bzoj1188: [HNOI2007]分裂游戏
- 关于界面滚动条的问题
- java并发(四) CopyOnWrite容器
- Stream的Dropzonejs样式演示
- 谈谈java中成员变量与成员方法继承的问题
- java TCP/IP实现简单的多人聊天功能
- 小心“好主意”
- Proguard.cfg 配置
- 【Java多线程】之六:Synchronization and Thread Safety
- jQuery
- Tarena - 数字求和小游戏
- house robberII
- C/S与B/S的区别
- POJ 3368 Frequent values
- Android蓝牙开发
- HDU 1017