Partition List
给一个链表, 和一个值x. 以x为pivot做partition.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode partition(ListNode head, int x) { if(head == null) return null; ListNode bhead = new ListNode(0); ListNode shead = new ListNode(0); ListNode pb = bhead; ListNode sb = shead; while(head != null) { if(head.val < x){ sb.next = head; sb = sb.next; }else{ pb.next = head; pb = pb.next; } head = head.next; } pb.next = null; sb.next = bhead.next; return shead.next; } } |