Simple and clean java code

  • 6
    public ListNode insertionSortList(ListNode head) {
    	ListNode cur = head;
    	ListNode dummy = new ListNode(0), p;
    	while (cur != null) {
    		//locate the insertion position.
    		p = dummy;
    		while ( != null &&  cur.val > {
    			p =;
    		//insert between p and
    		ListNode pNext =; = cur;
    		ListNode next =; = pNext;
    		cur = next;

  • 0
    This post is deleted!

  • 0

    When you insert between p and, you did not make = I don't understand why it is got accepted. Can someone help me understand it? Thanks!

  • 0

    Usually we find a descending node first, take it out and insert it into the correct position. But the above snippet actually takes out every single node and insert it, so it's not necessary to make = because it's rebuilding the whole list one by one (which is not the best solution).

  • 0

    Got it! Thanks a lot!

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.