难度

  • 简单
  • 中等
  • 困难

    标签

    链表

    题目描述

    编写程序以 x 为基准分割链表,使得所有小于 x 的节点排在大于或等于 x 的节点之前。如果链表中包含 x,x 只需出现在小于 x 的元素之后(如下所示)。分割元素 x 只需处于“右半部分”即可,其不需要被置于左右两部分之间。

    示例1:

    ```java 输入: head = 3->5->8->5->10->2->1, x = 5 输出: 3->1->2->10->5->5->8
  1. <a name="P3fYt"></a>
  2. ## 题解
  3. ```java
  4. /**
  5. * Definition for singly-linked list.
  6. * public class ListNode {
  7. * int val;
  8. * ListNode next;
  9. * ListNode(int x) { val = x; }
  10. * }
  11. */
  12. class Solution {
  13. public ListNode partition(ListNode head, int x) {
  14. ListNode smallHead = new ListNode(0);
  15. ListNode largeHead = new ListNode(0);
  16. ListNode small = smallHead;
  17. ListNode large = largeHead;
  18. ListNode cur = head;
  19. while(cur != null) {
  20. if(cur.val >= x) {
  21. large.next = cur;
  22. large = large.next;
  23. } else {
  24. small.next = cur;
  25. small = small.next;
  26. }
  27. cur = cur.next;
  28. }
  29. small.next = largeHead.next;
  30. large.next = null;
  31. return smallHead.next;
  32. }
  33. }