隊列是一種先進先出的一種數據結構。就像排隊一樣先到先買。從最後插入,從第一個拿出。這樣就實現了一個簡單隊列
ArrayList 是基於我自己實現的動態數組的 有需求的朋友可以看看。https://blog.csdn.net/xulinglin520/article/details/81514153
import java.util.ArrayList;
/**
*
* @author XiaoTian
* @date 2018-08-09
* @param <E>
*/
public class Queue<E> {
ArrayList<E> arrayList;
/**
*
* @param capacity
*/
public Queue(int capacity){
arrayList = new ArrayList<E>(capacity);
}
/**
* 無參構造器
*/
public Queue() {
arrayList = new ArrayList<E>();
}
public int size() {
return arrayList.size();
}
/**
* 向隊列末尾添加一個元素
* @param e
*/
public void push(E e) {
arrayList.add(e);
}
/**
* 取出隊列第一個元素
*/
public void remove() {
removeHead();
}
/**
* 刪除第一個元素
*/
public void removeHead(){ arrayList.remove(0);}
/**
* 判斷隊列是否爲空
* @return
*/
public boolean isEmpty() {
return size() > 0;
}
/**
* 查看隊列第一個元素
* @return
*/
public E getFront() {
return arrayList.get(0);
}
//打印(隊列)
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < size(); i++) {
buffer.append(arrayList.get(i));
if(i < size()-1) {
buffer.append("->");
}
}
return "Stack [ arrayList = top | " +
buffer.toString()
+ " ] ";
}
public static void main(String[] args) {
Queue<Integer> queue = new Queue<Integer>();
for (int i = 0; i < 10; i++) {
queue.push(i);
}
System.out.println(queue);
queue.remove();
System.out.println(queue);
queue.remove();
System.out.println(queue);
}
}
運行結果