Quicksort for LinkList
当年微软面试题: 少了两个= null, 结果木offer
public static ListNode sort(ListNode head){ if (head == null) return head; ListNode pivot = new ListNode(head.val); head = head.next; // remove pivot ListNode lessDummy = new ListNode(0); ListNode moreDummy = new ListNode(0); ListNode lessP = lessDummy; ListNode moreP = moreDummy; ListNode p = head; while (p != null){ if (p.val < pivot.val){ lessP.next = p; lessP = lessP.next; p = p.next; }else { moreP.next = p; moreP = moreP.next; p = p.next; } } lessP.next=null;//<-----当年少了这两个 moreP.next= null;//<---- lessDummy = sort(lessDummy.next); moreDummy = sort(moreDummy.next); lessP = lessDummy; moreP = moreDummy; if(lessP != null) { while (lessP.next != null) { lessP = lessP.next; } lessP.next = pivot; pivot.next = moreP; return lessDummy; } else { pivot.next = moreDummy; return pivot; } }
Leave A Comment