队列(Queue)
队列:在一端进入插入数据操作,在另一端进入删除数据操作的特殊线性表。队列具有先进先出的特性。入队是进行插入数据操作,出队为删除队列数据操作。
队列可以用数组和链表的结构实现,链表结构实现链式队列,数组结构实现顺序队列(循环队列)。
- 链式队列
示例代码:
class Node{
public int data;
public Node next;
public Node(int data){
this.data = data;
}
}
public class MyQueue {
public Node head;
public Node tail;
public int usedSize;
//入队
public boolean offer(int val){
Node node = new Node(val);
if (isEmpty()){
this.head = node;
this.tail = node;
}
this.tail.next = node;
this.tail = node;
this.usedSize++;
return true;
}
//出队
public int poll(){
if (isEmpty()){
return -1;
}
Node oldhead = this.head;
this.head = this.head.next;
this.usedSize--;
return oldhead.data;
}
//取队头数据
public int peek(){
if (isEmpty()){
return -1;
}
return this.head.data;
}
//判空
public boolean isEmpty(){
return this.usedSize == 0;
}
//返回长度
public int size(){
return this.usedSize;
}
}
//测试
public class Test {
public static void main(String[] args) {
MyQueue myQueue = new MyQueue();
myQueue.offer(4); //入队
myQueue.offer(3);
myQueue.offer(8);
System.out.println(myQueue.peek()); //4
System.out.println(myQueue.isEmpty()); //false
System.out.println(myQueue.size()); //3
System.out.println(myQueue.poll()); //4
System.out.println(myQueue.peek()); //3
}
}
- 顺序队列(循环队列)
示例代码:
public class MyCircularQueue{
public int[] elem;
public int front;
public int rear; //表示当前可以存放数据的下标
public MyCircularQueue(int k){
this.elem = new int[k];
}
//入队
public boolean enQueue(int val){
if (isFull()){
return false;
}
this.elem[this.rear] = val;
this.rear = (this.rear+1)%this.elem.length;
return true;
}
//判满
/*浪费一个空间,如果rear的下一个下标是front时,队列满*/
public boolean isFull(){
if ((this.rear+1)%this.elem.length == this.front){ //(this.rear+1)%this.elem.length 表示下一个空间
return true;
}
return false;
}
//判空
/*当front==raer时,队列为空*/
public boolean isEmpty(){
return this.front == this.rear;
}
//出队
public boolean deQueue(){
if (isEmpty()){
return false;
}
this.front = (this.front+1)%this.elem.length;
return true;
}
//取队头元素
public int Front(){
if (isEmpty()){
return -1;
}
return this.elem[this.front];
}
//取队尾元素
public int Rear(){
if (isEmpty()){
return -1;
}
int data = this.rear == 0 ? this.elem[this.elem.length-1] : this.elem[this.rear-1];
return data;
}
}
//测试
public class Test {
public static void main(String[] args) {
MyCircularQueue myCircularQueue = new MyCircularQueue(5);
myCircularQueue.enQueue(2);
myCircularQueue.enQueue(5);
myCircularQueue.enQueue(7);
myCircularQueue.enQueue(13);
System.out.println(myCircularQueue.isEmpty()); //false
System.out.println(myCircularQueue.Front()); // 2
myCircularQueue.deQueue();
System.out.println(myCircularQueue.Front()); // 5
System.out.println(myCircularQueue.Rear()); // 13
}
}