将单向链表按某值划分成左边小、中间相等、右边大的形式

来源:互联网 发布:如何考上清华知乎 编辑:程序博客网 时间:2024/03/29 19:55

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 headNode sT = null; // small tailNode eH = null; // equal headNode eT = null; // equal tailNode bH = null; // big headNode bT = null; // big tailNode next = null; // save next node// every node distributed to three listswhile (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 reconnectif (sT != null) {sT.next = eH;eT = eT == null ? sT : eT;}// all reconnectif (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);}}


阅读全文
0 0