队列和栈刚好相反啦,是先进先出的线性表
它只能在表的一端进行插入,另一端进行删除元素
允许插入的一端叫做队尾,允许删除的一端叫做队头
循环队列
class QueueDemo{
private int front;
private int rear;
private int[] elem;
private int usedSize = 0;
private int allSize = 10;
public QueueDemo(){
this(10);
}
public QueueDemo(int size){
this.front = 0;
this.rear = 0;
this.elem = new int[size];
}
//入队
public void push(int val){
if (isFull()){
return;
}
this.elem[this.rear] = val;
this.rear = (this.rear+1) % allSize;
usedSize++;
}
//出队
public int pop(){
if (isEmpty()){
throw new UnsupportedOperationException("队列为空");
}
int num = this.elem[front];
this.elem[this.front] = -1; //如果对列里面是引用,这里置为null
this.front = (this.front+1) % allSize;
this.usedSize--;
return num;
}
//判空
public boolean isEmpty(){
if (this.rear == this.front){
return true;
}
return false;
}
//判满
public boolean isFull(){
if ((this.rear + 1) % allSize == this.front){
return true;
}
return false;
}
//打印
public void show(){
for (int i = this.front; i != this.rear; i = (i+1) % allSize) {
System.out.printf(this.elem[i]+" ");
}
System.out.println();
}
}
测试
public class TestQueueDemo {
public static void main(String[] args) {
QueueDemo queueDemo = new QueueDemo();
for (int i = 0; i < 8; i++) {
queueDemo.push(i);
}
queueDemo.show();
queueDemo.pop();
queueDemo.show();
}
}
链式队列
class LinkQueue{
class Entry{
int data;
Entry next;
public Entry(){
this.data = -1;
this.next = null;
}
public Entry(int val){
this.data = val;
this.next = null;
}
}
private Entry front; //头结点
private Entry rear; //尾结点
private int usedSize; //用过的大小
public LinkQueue(){
this.front = null;
this.rear = null;
this.usedSize = 0;
}
//入队
public void push(int val){
Entry entry = new Entry(val);
if (isEmpty()){ //空的话
this.front = entry; //队尾和队头都指向entry
this.rear = this.front;
}else { //非空
this.rear.next = entry; //队尾插入
this.rear = this.rear.next; //队尾向后走
}
this.usedSize++; //用过的大小加一
}
//出队
public int pop(){
if (isEmpty()){
throw new UnsupportedOperationException("队列为空");
}
Entry delete = this.front; //队头出队
this.front = delete.next; //front后移
this.usedSize--; //用过的大小减一
return delete.data;
}
//判空
public boolean isEmpty(){
if (this.usedSize == 0){
return true;
}
return false;
}
//打印
public void show(){
Entry cur = this.front;
while (cur != null){
System.out.print(cur.data+" ");
cur = cur.next;
}
System.out.println();
}
}
测试
public class LinkQueueDemo {
public static void main(String[] args) {
LinkQueue linkQueue = new LinkQueue();
for (int i = 0; i < 10; i++) {
linkQueue.push(i);
}
linkQueue.show();
linkQueue.pop();
linkQueue.show();
}
}