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

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



浙公网安备 33010602011771号