题目

image.png

思路

  • 使用虚拟节点和尾插法

    代码

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