147. Insertion Sort List【M】Java
2016-02-29 15:41
387 查看
Sort a linked list using insertion sort.
Subscribe to see which companies asked this question
python 和java的代码
python的代码过不了5000的case
Subscribe to see which companies asked this question
python 和java的代码
python的代码过不了5000的case
class Solution(object): def insertionSortList(self, head): if head == None or head.next == None: return head helper = ListNode(0) cur = head #the node will be inserted pre = helper # insert the node after pre next = None # the next node will be inserted while cur: next = cur.next while pre.next and pre.next.val < cur.val: pre = pre.next cur.next = pre.next pre.next = cur pre = helper cur = next return helper.next
public class Solution { public ListNode insertionSortList(ListNode head) { if( head == null ){ return head; } ListNode helper = new ListNode(0); //new starter of the sorted list ListNode cur = head; //the node will be inserted ListNode pre = helper; //insert node between pre and pre.next ListNode next = null; //the next node will be inserted //not the end of input list while( cur != null ){ next = cur.next; //find the right place to insert while( pre.next != null && pre.next.val < cur.val ){ pre = pre.next; } //insert between pre and pre.next cur.next = pre.next; pre.next = cur; pre = helper; cur = next; } return helper.next; } }
相关文章推荐
- eclipse一直报An internal error occurred during: "Building workspace". GC overhead limit exceeded
- java39.Socket通信------使用 Java 创建聊天客户端(未完待续。。。)
- myeclipse内存不足解决方案
- Java线程池
- Java 反射机制浅析
- java编写简单的E-mail发送端程序
- myeclipse个人注释模板
- java api文档的使用
- Java实现简单邮件发送
- JAVA中值类型和引用类型的不同?
- spring-jms的pom.xml
- 《JAVA与模式》学习之装饰模式
- java学习笔记-抽象类abstract与接口interface
- Struts,Hibernate,spring工作机制
- java server
- Java回调机制解析
- JAVA学习【9】 集合框架TreeSet类和TreeMap类的排序
- JAVA 基础之 异常机制
- JAVA_猜数字
- java 中线程执行顺序控制