您的位置:首页 > 理论基础 > 数据结构算法

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

2017-09-07 14:55 1041 查看
队列是一种特殊的线性表,它只允许从队列首(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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: