队列(先进先出)
顺序表存储
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; }
栈(先进后出)
时间: 2024-12-13 19:19:21