直接创建两个链表,一个放小于x的元素,另一个链表大于或等于x的元素。
等到都分完了就合并一下。
public LinkedListNode partition(LinkedListNode node, int x) { LinkedListNode beforeStart = null; LinkedListNode beforeEnd = null; LinkedListNode afterStart = null; LinkedListNode afterEnd = null; while (node != null) { LinkedListNode next = node.next; node.next = null; if (node.data < x) { if (beforeStart == null) { beforeStart = node; beforeEnd = beforeStart; } else { beforeEnd.next = node; beforeEnd = node; } } else { if (afterStart == null) { afterStart = node; afterEnd = afterStart; } else { afterEnd.next = node; afterEnd = node; } } node = next; } if (beforeStart == null) { return afterStart; } beforeEnd.next = afterStart; return beforeStart; }