链表分割为下图:
实现代码:
public Node partition(int x) {
Node beforeStart = null;
Node beforeEnd = null;
Node afterStart = null;
Node afterEnd = null;
Node pHead = this.head;
while (pHead != null) {
Node pHeadNext = pHead.next;
pHead.next = null;
//插入值比x小,放在前一个链表中
if (pHead.data < x) {
//当前一个链表元素为空时
if (beforeStart == null) {
beforeStart = pHead;//尾插法
beforeEnd = beforeStart;
} else {
beforeEnd.next = pHead;
beforeEnd = pHead;
}
//插入值比x大,放在后一个链表中
} else {
//当后一个链表元素为空时
if (afterStart == null) {
afterStart = pHead;//尾插法
afterEnd = afterStart;
} else {
afterEnd.next = pHead;
afterEnd = pHead;
}
}
pHead = pHeadNext;//pHead遍历整个链表
}
if (beforeStart == null){
return afterStart;
}
beforeEnd.next = afterStart;
return beforeStart;
}
//打印函数
public void show(Node partition){
Node cur = partition;
while(cur != null) {
System.out.print(cur.data+" ");
cur = cur.next;
}
System.out.println();
}