将单向链表按某值划分成左边小、中间相等、右边大的形式
程序员文章站
2022-05-06 11:33:25
...
import java.util.LinkedList;
import java.util.Queue;
//将单向链表按某值划分成左边小、中间相等、右边大的形式
public class DivideList{
//链表节点的定义
public static class Node{
public int value;
public Node next;
public Node(int data)
{
this.value=data;
}
}
//将单向链表值进行划分
public static Node Dividelist(Node head,int pivot)
{
if(head==null)
{
return head;
}
Node p=head;
Queue <Node>queue1=new LinkedList<Node>(); //存储比pivot大的数
Queue <Node>queue2=new LinkedList<Node>(); //存储和pivot小的数
Queue <Node>queue3=new LinkedList<Node>(); //存储和pivot相等的数
while(p!=null)
{
if(p.value>pivot)
{
queue1.offer(p);
}else if(p.value<pivot)
{
queue2.offer(p);
}
else
{
queue3.offer(p);
}
p=p.next;
}
Node t=head;
while(!queue2.isEmpty())
{
System.out.print(queue2.poll().value+" ");
//t.value=queue2.poll().value;
//t=t.next;
}
while(!queue3.isEmpty())
{
System.out.print(queue3.poll().value+" ");
//t.value=queue3.poll().value;
//t=t.next;
}
while(!queue1.isEmpty())
{
System.out.print(queue1.poll().value+" ");
//t.value=queue1.poll().value;
//t=t.next;
}
return head;
}
//进阶方法 需要时间复杂度O(N),空间复杂度为O(1)
public static Node Dividelist2(Node head, int pivot) {
Node sH = null; // small head
Node sT = null; // small tail
Node eH = null; // equal head
Node eT = null; // equal tail
Node bH = null; // big head
Node bT = null; // big tail
Node next = null; // save next node
// every node distributed to three lists
while (head != null) {
next = head.next;
head.next = null;
if (head.value < pivot) {
if (sH == null) {
sH = head;
sT = head;
} else {
sT.next = head;
sT = head;
}
} else if (head.value == 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;
}
// small and equal reconnect
if (sT != null) {
sT.next = eH;
eT = eT == null ? sT : eT;
}
// all reconnect
if (eT != null) {
eT.next = bH;
}
return sH != null ? sH : eH != null ? eH : bH;
}
//打印链表
public static void PrintList(Node head)
{
while(head!=null)
{
System.out.print(head.value+" ");
head=head.next;
}
System.out.println();
}
public static void main(String []args)
{
//System.out.println("Hello");
Node node=new Node(9);
node.next=new Node(0);
node.next.next=new Node(4);
node.next.next.next=new Node(5);
node.next.next.next.next=new Node(1);
PrintList(node);
//Node mode=Dividelist1(node,3);
Node mode=Dividelist2(node,3);
PrintList(mode);
}
}
下一篇: 剑指Offer23-从尾到头打印链表