用三个桶,每个桶包括(链表的头和链表的尾),三个桶分别是Less, Equal, More.遍历一次链表把数值放入相应的桶。
public class Test_Demo {
public static class Node{
int value;
Node next;
public Node(int value) {
this.value=value;
}
}
public static Node LessEqualMore(Node head,int num) {
if(head==null)
return head;
Node lessStart=null;
Node lessEnd=null;//第一个桶
Node equalStart=null;
Node equalEnd=null;//第二个桶
Node moreStart=null;
Node moreEnd=null;//第三个桶
Node next=null;
while(head!=null)//遍历一次
{
next=head.next;
head.next=null;
if(head.value<num)
{
if(lessStart==null)
lessStart=head;
else
lessEnd.next=head;
lessEnd=head;
}
else if(head.value==num)
{
if(equalStart==null)
equalStart=head;
else
equalEnd.next=head;
equalEnd=head;
}
else if(head.value>num)
{
if(moreStart==null)
moreStart=head;
else
moreEnd.next=head;
moreEnd=head;
}
head=next;
}
if(lessEnd!=null)//拼接三个桶
{
if(equalStart!=null)
{
lessEnd.next=equalStart;
if(moreStart!=null)
equalEnd.next=moreStart;
}
else if(moreStart!=null)
lessEnd.next=moreStart;
}
else if(equalEnd!=null)
{
if(moreStart!=null)
equalEnd.next=moreStart;
}
return lessStart=lessStart==null?(equalStart==null?moreStart:equalStart):lessStart;//返回头结点
}
public static void printLinkedList(Node head) {
System.out.println("The LinkedList is :");
while(head!=null)
{
System.out.print(head.value+" ");
head=head.next;
}
System.out.println();
}
public static void main(String[] args) {
Node head = new Node(7);
head.next = new Node(9);
head.next.next = new Node(1);
head.next.next.next = new Node(8);
head.next.next.next.next = new Node(5);
head.next.next.next.next.next = new Node(2);
head.next.next.next.next.next.next = new Node(5);
printLinkedList(head);
head=LessEqualMore(head,5);
printLinkedList(head);
}
}
另一种方法就是把节点存入数组中,再根据数组的荷兰国旗问题求解。