数组实现
package com.queue;
public class Queue_array {
private int[] queue;
private int size;
private int h,t;//h队头 t队尾
public Queue_array()
{
this(5);
}
public Queue_array(int n)
{
queue = new int[n];
size = 0;
h=-1;
t=0;
//其中 我的h,t规定是这样的 h在队顶元素的前一个位置 t在队尾元素的后一个位置 在队列为空时 h-t = 1;
}
/*
* 插入队列
*/
public void offer(int n)
{
if(t == queue.length)//拓展队列
queue = expend(queue);
queue[t] = n;
t++;
size++;
}
/*
* 弹出队顶元素
*/
public int pop()
{
if(t-h == 1)
{
System.out.print("队列为空");
return -1;//当做抛出一个异常
}
size--;
h++;
return queue[h];
}
/*
* 查看队顶元素
*/
public int peak()
{
if(t-h == 1)
{
System.out.print("队列为空");
return -1;//当做抛出一个异常
}
return queue[1+h];
}
public int size()
{
return size;
}
public boolean isEmpty()
{
return size == 0;
}
/*
* 拓展队列空间
*/
private int[] expend(int[] q) {
int[] newQ = new int[q.length+5];
for(int i=0;i<q.length;i++)
{
newQ[i] = q[i];
}
return newQ;
}
}
循环队列
package com.queue;
public class Queue_circul {
private int rear;//头
private int front;//尾
private int maxSize;//最大容量
private int[] arr;//数组队列
public Queue_circul(){
this(5);
}
public Queue_circul(int n) {
rear = front = 0;
maxSize = n;
arr = new int[n];
}
/*
*判空 rear == front
*判满 (rear+1)%size = front
*/
public void offer(int n)
{
if((rear+1)%maxSize == front)//判满
arr = expand(arr);//拓容
arr[rear] = n;
rear = (rear+1)%maxSize;
}
public int pop()
{
if(rear == front)
{
System.out.println("队列为空");
return -1;
}
int val = arr[front];
front = (front+1)%maxSize;
return val;
}
public int peak()
{
if(rear == front)
{
System.out.println("队列为空");
return -1;
}
return arr[front];
}
public int size()
{
return (rear-front+maxSize)%maxSize;
}
/*
* attention!
* 拓展队列
*/
private int[] expand(int[] a) {
int[] temp = new int[a.length+5];
for(int i=front;i<front+size();i++)
{
temp[i] = a[i%maxSize];//第一正确复制元素 元素数量和相对顺序以及其值都必须保持不变
}
maxSize = temp.length;//第二改变最大容量
rear = (front+size())%temp.length;//第三改变队尾指针
return temp;
}
public boolean isEmpty()
{
return rear == front;
}
}
> 链式实现
```java
package com.queue;
public class Queue_link {
class Node
{
int val;
Node next;
public Node(int n)
{
val = n;
next = null;
}
}
private Node h;
private Node t;
private int size;
public Queue_link()
{
}
/*
* 插入
*/
public void offer(int n)
{
Node node = new Node(n);
if(h == null)//如果h指针为空说明 队列为空
{
h = node;
t = h;
}else
{
t.next = node;
}
t = node;
size++;
}
/*
* 弹出队顶元素
*/
public int pop()
{
int val = peak();
if(h != null)
{
h = h.next;
size--;
}
return val;
}
/*
* 查看队顶元素
*/
public int peak() {
if(h==null)
{
System.out.print("队列为空");
return -1;//当做异常抛出
}
return h.val;
}
public int size()
{
return size;
}
public boolean isEmpty()
{
return size == 0;
}
}