zoukankan      html  css  js  c++  java
  • 队列与栈

     
     

    队列(先进先出)

    顺序表存储

    front:出队指针
    rear:入队指针
     
    从下往上走:
         (可以出现队空状态)         
               (不可以出现队满状态,即数组至少有一个为空)
    类成员
    1.     private T[]queue;
    2.     privatestaticint size =20;         //队列容量
    3.     privateint front, rear;        //队首、队尾下标
    初始化
    1.     publicArrayQueue(){
    2.         queue=(T[])newObject[size];
    3.         front =0;
    4.         rear =0;
    5.     }
    入队
    1.      publicvoid add(T t) throws Exception
    2.     {
    3.         if((rear +1)% size == front)
    4.             thrownewException("over flow!");
    5.  
    6.         rear =(rear +1)% size;
    7.         queue[rear]= t;
    8.     }
    出队
    1.      public T poll() throws Exception
    2.     {
    3.         if(front == rear)
    4.             thrownewException("under flow!");
    5.  
    6.         front =(front +1)% size;
    7.         returnqueue[front];
    8.     }
    判空
    1.     public boolean isEmpty(){
    2.         return front == rear;
    3.     }
     

    链式存储

     
    类成员
    1.  //结点类
    2.     publicclassNode{
    3.         public T data;
    4.         publicNode next;
    5.  
    6.         publicNode(T obj,Node next){
    7.             this.data = obj;
    8.             this.next = next;
    9.         }
    10.     }
    11.  
    12.     privateNode head,front,rear;
    初始化
    1. publicLinkQueue(){
    2.         head =newNode(null,null);
    3.         front = rear = head;
    4.         size =0;
    5.  }
     
    入队
    1.  //从队尾入队
    2.     publicvoid add(T t)
    3.     {
    4.         Node s =newNode(t,null);
    5.         rear.next = s;
    6.         rear = s;
    7.         size++;//队列长度+1
    8.     }
    出队
    1.     //从队头出队
    2.     public T poll() throws Exception
    3.     {
    4.         if(rear == front)
    5.             thrownewException("under flow!");
    6.  
    7.         Node temp = front.next;           //暂存队首,以便返回
    8.         front.next = front.next.next;
    9.  
    10.         if(front.next == null)          //最后一个元素出队:还要对队尾处理
    11.             rear = front;
    12.  
    13.         return temp.data;
    14.     }
     

    栈(先进后出)

     
     
     
     
     
     





  • 相关阅读:
    Elementary Methods in Number Theory Exercise 1.2.25
    Elementary Methods in Number Theory Exercise 1.2.14
    图解欧几里德算法
    图解欧几里德算法
    Elementary Methods in Number Theory Exercise 1.2.14
    Android中的长度单位详解(dp、sp、px、in、pt、mm)
    分享下多年积累的对JAVA程序员成长之路的总结
    android异常之都是deamon惹的祸The connection to adb is down, and a severe error has occured.
    TomatoCartv1.1.8.2部署时报错
    JavaScript浏览器对象之二Document对象
  • 原文地址:https://www.cnblogs.com/Doing-what-I-love/p/5445067.html
Copyright © 2011-2022 走看看