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

数据结构之队列【java实现】

2016-10-24 10:58 609 查看
用java代码实现了先入先出的队列数据结构,该类中包括构造方法,向队列尾部插入元素,从队列头部移除元素,判断队列为空,判断队列已满,打印队列元素等方法,并给出实例验证,以下是原代码:

package struct;

import java.util.Scanner;

public class Queue {
private int maxSize;
private int[] queArray;
private int front;
private int rear;
private int num;

/*
* 构造函数
* 初始化队列
*/
public Queue(int s) {
maxSize = s;
queArray = new int[maxSize];
front = 0;
rear = -1;
num = 0;
}

/*
* 从队列的尾部插入元素
* 尾部加一,个数加一,如果尾部达到数组最大值了,就回到初始值-1
*/
public void insert(int value) {
if (rear == maxSize - 1) {
rear = -1;
} else {
queArray[++rear] = value;// 将元素插入队列尾部
num++;// 队列的元素个数加一
}
}

/*
* 从队列的头部取出元素
* 头部加一,个数减一,当头部达到数组最大值时,回到初始值0;
*/
public int remove() {
int temp = queArray[front++];
int a = -1;
if (front == maxSize) {
front = 0;
}
num--;
a = temp;
return a;
}

/*
* 打印队列中的元素
* 借用移除元素方法打印队列中的元素,
* 需要注意的是:移除所有元素后,头部和尾部都不会发生改变,只有数量会发生改变;
* 所以在使用移除元素方法之前,应该把数量记录下来,并且最后返回;
*/
public void display(){
int temp = num;
while(!isEmpty()){
System.out.print(remove()+" ");
}
System.out.println();
num = temp;
}

/*
* 判断队列是否为空
* 当数量为0时,队列为空
*/
public boolean isEmpty() {
return (num == 0);
}

/*
* 判断队列是否已满
* 当数量等于数组最大值时,队列为满
*/
public boolean isFull() {
return (num == maxSize);
}

// 返回队列的元素个数
public int size() {
return num;
}

public static void main(String[] args) {
Queue queue = new Queue(10);
Scanner scan = new Scanner(System.in);
while(!queue.isFull()){
int value = scan.nextInt();
queue.insert(value);
}
System.out.println("插入元素之后:");
queue.display();
queue.remove();
queue.remove();
System.out.println("移除两个元素之后:");
queue.display();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构