题解 | #链表分割#
链表分割
https://www.nowcoder.com/practice/0e27e0b064de4eacac178676ef9c9d70
import java.util.*; /* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Partition { public ListNode partition(ListNode pHead, int x) { // write code here ListNode bs = null; ListNode be = null; ListNode as = null; ListNode ae = null; ListNode cur = pHead; while (cur != null) { if (cur.val < x) { if (bs == null) { bs = cur; be = cur; } else { be.next = cur; be = be.next; } } else { if (as == null) { as = cur; ae = cur; } else { ae.next = cur; ae = ae.next; } } cur = cur.next; } // 特殊情况一:没有小于x的节点 if (be == null) { return as; } // 特殊情况二:ae.next != null,造成死循环 if (as != null) { ae.next = null; } be.next = as; return bs; } }