Leetcode-insertion-sort-list ***
2016-07-17 17:18
405 查看
题目描述
Sort a linked list using insertion sort.题目越短,事情越大。
用插入排序法对链表进行排序。
我是参考别人的解答做的,这题我不会。
* public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode insertionSortList(ListNode head) { if(head == null || head.next == null) return head; ListNode cursors = head; ListNode tempCur = null; ListNode temp = head; //待排序元素的上一个 元素 ListNode current = temp.next; //待排序元素 while(current != null){ if(current.val < head.val){ temp.next = current.next; //待排序元素上一个元素指向待排序元素下一个元素 current.next = head; head = current; }else{ // cursors-↓ ↓-temp // 1 -> 3 -> 5 -> 8 -> 4-> 12 -> 2 //tempCur-↑ current-↑ //插入后: // |-------有序---------| // 1 -> 3 -> 4 -> 5 -> 8-> 12 -> 2 //找到插入的位置 current插入到cursors的前面:temp->current->cursors tempCur = cursors; cursors = tempCur.next; while(cursors != current && cursors.val < current.val){ tempCur = cursors; cursors = cursors.next; } if(cursors == current){ temp = current; current = temp.next; }else{ temp.next = current.next; tempCur.next = current; current.next = cursors; } } cursors = head; current = temp.next; } return head; } }
数组的插入排序是从待排序元素往前找插入位置,而链表则是从头开始找插入位置。
相关文章推荐
- Svg存在的坑
- 万能的搜索之再解炸弹人
- NSLayoutConstraint - 系统自动布局(详解)
- Javascript 面向对象编程(一):封装
- DrawerLayout与FragmentTabHost结合模仿oschina主界面
- Word 2013自定义样式
- POJ 2337 欧拉回路
- float与行框 --- 文字围绕浮动之谜
- POJ 2337 欧拉回路
- 动态添加菜单栏Pluse
- java范型
- maven中下载jar包源码和javadoc的命令介绍
- centos下samba服务器的安装与配置
- EL表达式
- 窄带信号和宽带信号的区别和联系
- Python *** 爬下糗事百科数据
- 判断一棵二叉树是否为对称的 java
- ARM代码的编译与链接调试
- 浅谈中文分词法
- Give My Text Back