image.png

解决思路

链表

用两个链表,一个链表放小于x的节点,一个链表放大于等于x的节点
最后,拼接这两个链表.

  1. public ListNode partition(ListNode head, int x) {
  2. ListNode dummy1 = new ListNode(-1);
  3. ListNode dummy2 = new ListNode(-1);
  4. ListNode p1 = dummy1;
  5. ListNode p2 = dummy2;
  6. while (head != null) {
  7. if (head.val < x) {
  8. p1.next = head;
  9. p1 = p1.next;
  10. } else {
  11. p2.next = head;
  12. p2 = p2.next;
  13. }
  14. head = head.next;
  15. }
  16. p1.next = dummy2.next;
  17. p2.next = null;
  18. return dummy1.next;
  19. }