题目
例如 链表 1-2-3-6-7-8-5-4-9-10 ,按 5分为左边小,中间相等,右边大的链表,1-2-3-4-5-6-7-8-9-10
java代码
/**
* @Description:将单链表按某值划分为左边小,中间相等,右边大的链表
* @Author: lizhouwei
* @CreateDate: 2018/4/6 21:26
* @Modify by:
* @ModifyDate:
*/
public class Chapter2_8 {
public Node partition(Node head, int pivot) {
if (head == null) {
return null;
}
Node sH = null;//小的链表的头节点
Node sT = null;//小的链表的尾节点
Node eH = null;//相等的链表的头节点
Node eT = null;//相等的链表的头节点
Node bH = null;//大的链表的头节点
Node bT = null;//大的链表的尾节点
Node next = null;
while (head != null) {
next = head.next;
head.next = null;
if (head.vlaue < pivot) {
if (sH == null) {
sH = head;
sT = head;
} else {
sT.next = head;
sT = head;
}
} else if (head.vlaue == pivot) {
if (eH == null) {
eH = head;
eT = head;
} else {
eT.next = head;
eT = head;
}
} else {
if (bH == null) {
bH = head;
bT = head;
} else {
bT.next = head;
bT = head;
}
}
head = next;
}
//重新连接
if (sT != null) {
sT.next = eH;
eT = eT == null ? sT : eT;
}
if (eT != null) {
eT.next = bH;
}
return sH != null ? sH : eH != null ? eH : bH;
}
//测试
public static void main(String[] args) {
Chapter2_8 chapter = new Chapter2_8();
Link link = new Link();
//构造两个链表
for (int i = 10; i > 0; i--) {
link.add(i);
link.add(i + 10);
}
Link.printLink(link.head);
Node head = chapter.partition(link.head, 10);
Link.printLink(head);
}
}