数组实现队列
程序员文章站
2022-03-14 15:06:09
...
权当个人笔记
package com.zyw.collection.queue;
/**
* target:using array to realize Bi-directional circulation Queue.
* first-in-first-out
* @author KeepGoingPawn
* @date 2018.06.25
*/
public class Queue {
private int[] space = null;//the space of queue.
private int head = 0;//the head index of queue.
private int tail = 0;//the tail index of queue.
private int maxLength = 0;//the max length of queue.
/**
* The constructor method of having params.
* @param length
*/
public Queue(int length){
this.maxLength = length;
space = new int[length];
}
/**
* The realize of push's method
*/
public void push(int x){
if(isFull()){
System.out.println("The queue is full.");
}
space[tail] = x;
tail = (tail+1) % maxLength;
}
/**
* the realize of pop's method
*/
public void pop(){
if(isEmpty()){
System.out.println("The queue is empty.");
}
head = (head+1) % maxLength;
}
/**
* watch the head element
* @return
*/
public int front(){
return space[head];
}
/**
* watch the tail element
* @return
*/
public int back(){
return space[(tail+maxLength-1) % maxLength];
}
/**
* watch the total num of the queue.
* @return
*/
public int size(){
return (tail +maxLength-head) % maxLength;
}
/**
* judge the queue is empty or not.
* @return
*/
public boolean isEmpty(){
if(tail == head){
return true;
}
return false;
}
/**
* judge the queue is full or not.
* @return
*/
public boolean isFull(){
//If the tail's next index is head,indicates that the queue is full.
if((tail+1) % maxLength == head){
return true;
}
return false;
}
public static void main(String[] args) {
Queue q = new Queue(5);
q.push(1);
q.push(2);
q.push(3);
q.push(4);
System.out.println("front's element:"+q.front()+" tail's element:"+q.back()+" the total's num:"+q.size());
q.push(4);
q.push(5);
q.push(6);
q.pop();
q.pop();
q.push(7);
System.out.println("front's element:"+q.front()+" tail's element:"+q.back()+" the total's num:"+q.size());
}
}
上一篇: 自动驾驶这个“小孩子”有多大了?