隊列
隊列是先進先出,與堆棧不一樣
數組實現
數組實現主要採用雙指針方式
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;
}
}