2.4编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或者等于x的结点之前。
直接创建两个链表,一个放小于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; }