本文主要是介绍147. Insertion Sort List【M】Java,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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 headhelper = ListNode(0)cur = head #the node will be insertedpre = helper # insert the node after prenext = None # the next node will be insertedwhile cur:next = cur.nextwhile pre.next and pre.next.val < cur.val:pre = pre.nextcur.next = pre.nextpre.next = curpre = helpercur = nextreturn 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 listListNode cur = head; //the node will be insertedListNode pre = helper; //insert node between pre and pre.nextListNode next = null; //the next node will be inserted//not the end of input listwhile( cur != null ){next = cur.next;//find the right place to insertwhile( pre.next != null && pre.next.val < cur.val ){pre = pre.next;}//insert between pre and pre.nextcur.next = pre.next;pre.next = cur;pre = helper;cur = next;}return helper.next;}
}
这篇关于147. Insertion Sort List【M】Java的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!