队列
队列是先进先出,与堆栈不一样
数组实现
数组实现主要采用双指针方式
package com.example.data;
/**
* *@ClassName QueueList
* *@Author yyc
* *@Date 2020/6/15 15:15
**/
public class QueueList {
//头指针
private int Head;
//尾指针
private int Tail;
private int[] result;
private int len;
//初始化队列数组
public QueueList(int length)
{
this.len=length;
this.result=new int[length];
this.Head=0;
this.Tail=0;
}
//往队列中压入数据
public void Enqueue(int value)
{
if(Tail<len)
{
result[Tail++] = value;
}
}
public int Dequeue() throws Exception {
if(Head<=Tail)
{
return result[Head++];
}
else
throw new Exception("超出范围");
}
}
链表队列
package com.example.data;
/**
* *@ClassName QueueLinked
* *@Author yyc
* *@Date 2020/6/15 16:17
* 链表队列
**/
public class QueueLinked {
//头链表
public Node head;
//尾链表
public Node Tail;
//链表长度
private int N;
public QueueLinked(){
head=new Node(null,null);
Tail=null;
N=0;
}
/**
* 判断是否为空链表
* @return
*/
public boolean isEmpty(){
return N==0;
}
public void push(Integer value)
{
if(Tail==null)
{
Tail=new Node(value,null);
head.next=Tail;
}
else
{
Node oldLast=Tail;
Tail=new Node(value,null);
oldLast.next=Tail;
}
N++;
}
public Integer pop(){
if(isEmpty()) {
return null;
}
Node oldFirst=head.next;
head.next=oldFirst.next;
N--;
if(isEmpty())
{
Tail=null;
}
return (Integer) oldFirst.item;
}
}