zoukankan      html  css  js  c++  java
  • 队列(链式存储)JAVA代码

     
    1. publicclassLinkQueue<T>{
    2.  
    3.     //结点类
    4.     publicclassNode{
    5.         public T data;
    6.         publicNode next;
    7.  
    8.         publicNode(T obj,Node next){
    9.             this.data = obj;
    10.             this.next = next;
    11.         }
    12.     }
    13.  
    14.     privateNode head,front,rear;
    15.  
    16.     publicLinkQueue(){
    17.         head =newNode(null,null);
    18.         front = rear = head;
    19.         size =0;
    20.     }
    21.  
    22.     //从队尾入队
    23.     publicvoid add(T t)
    24.     {
    25.         Node s =newNode(t,null);
    26.         rear.next = s;
    27.         rear = s;
    28.         size++;//队列长度+1
    29.     }
    30.  
    31.     //从队头出队
    32.     public T poll() throws Exception
    33.     {
    34.         if(rear == front)
    35.             thrownewException("under flow!");
    36.  
    37.         Node temp = front.next;           //暂存队首,以便返回
    38.         front.next = front.next.next;
    39.  
    40.         if(front.next == null)          //最后一个元素出队:还要对队尾处理
    41.             rear = front;
    42.  
    43.         return temp.data;
    44.     }
    45.  
    46.     public boolean isEmpty(){
    47.         return front == rear;
    48.     }
    49.  
    50. }
     
    1.  LinkQueue<String> q =newLinkQueue<String>();
    2.         q.add("a");
    3.         q.add("b");
    4.         q.add("c");
    5.         q.add("d");
    6.         q.add("e");
    7.         q.add("f");
    8.         q.add("g");
    9.         q.add("h");
    10.         q.add("i");
    11.         q.add("j");
    12.         q.add("k");
    13.         q.add("l");
    14.         q.add("m");
    15.         while(!q.isEmpty()){
    16.             String temp = q.poll();
    17.             System.out.print(temp);
    18.         }
     
    输出
    1. abcdefghijklm
     
     





  • 相关阅读:
    设计模式之桥接模式
    设计模式之适配器模式
    设计模式之代理模式
    设计模式之建造者模式
    设计模式之抽象工厂模式
    设计模式之工厂方法模式
    设计模式之简单工厂模式
    设计模式之原型模式
    api接口测试的步骤
    3种优化回归测试的方法
  • 原文地址:https://www.cnblogs.com/Doing-what-I-love/p/5535012.html
Copyright © 2011-2022 走看看