public static void main(String[] args) { PartitionList pl = new PartitionList(); ListNode l1 = new ListNode(1); ListNode l2 = new ListNode(4); ListNode l3 = new ListNode(3); ListNode l4 = new ListNode(2); ListNode l5 = new ListNode(5); ListNode l6 = new ListNode(2); l1.next = l2; l2.next = l3; l3.next = l4; l4.next = l5; l5.next = l6; ListNode rtlist = pl.partition(l1, 3); while (rtlist != null) { System.out.println(rtlist.val); rtlist = rtlist.next; } }
public ListNode partition(ListNode head, int x) { // write your code here if (head == null) return head; ListNode greater = new ListNode(0); ListNode less = new ListNode(0); ListNode ptr = head; ListNode lp = less; ListNode gp = greater; while (ptr != null) { if (ptr.val < x) { lp.next = ptr; lp = lp.next; } else { gp.next = ptr; gp = gp.next; } ptr = ptr.next; } lp.next = greater.next; gp.next = null; return less.next; }