您的位置:首页 > 编程语言 > Java开发

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

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: