数据结构与算法(4)---Java语言实现:队列的单链表定义

来源:互联网 发布:2016年网络炒作事件 编辑:程序博客网 时间:2024/05/16 15:20

队列是一种特殊的线性表,它只允许从队列首(front)取数据,从队列尾(rear)插入数据,是一种FIFO(first in first out)结构。

package 数据结构;public class QueueList {private  int size;private Slinklist front;private Slinklist rear;public QueueList(){size=0;front=null;rear=null;}//返回队列大小public int getSize(){return size;}//判断队列是否为空public boolean isEmpty(){return size==0;}//入队列public void enqueue(int e){Slinklist m=new Slinklist(e, null);if (size==0){front=m;rear=m;}else {rear.setNext(m);//将入队列之前的队尾的下一个元素设为新元素rear=m;//将新元素设为队尾}size++;}//出队列public int dequeue() throws EmptyQueueListException{if (size==0) throw new EmptyQueueListException("队列为空,无法出队列");int m=front.getData();front=front.getNext();size--;return m;}//取队首元素public int peek() throws EmptyQueueListException{if(size==0) throw new EmptyQueueListException("队列为空,无法取得队首元素的值");int m=front.getData();return m;}}

空队列异常的定义:

package 数据结构;public class EmptyQueueListException extends RuntimeException{public EmptyQueueListException(String str){super(str);}}


阅读全文
0 0