队列与栈

 
 

队列(先进先出)

顺序表存储

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.     }
 

栈(先进后出)

 
 
 
 
 
 





原文地址:https://www.cnblogs.com/Doing-what-I-love/p/5445067.html