什么是隊列
隊列是一種基于先進先出(FIFO)的數(shù)據(jù)結構墨叛,是一種只能在一端進行插入,在另一端進行刪除操作的特殊線性表止毕,它按照先進先出的原則存儲數(shù)據(jù),先進入的數(shù)據(jù)漠趁,在讀取數(shù)據(jù)時先讀被讀出來扁凛;
代碼實現(xiàn)(通過雙向鏈表來實現(xiàn))
類名 | MyQueue |
---|---|
成員方法 | 1.public void clear():清空隊列 2.public boolean isEmpty():判斷隊列是否為空,是返回true闯传,否返回false 3.public int size():獲取隊列中元素的個數(shù) 4.public T get():從隊列中取出一個元素 5.public void push(T t):向隊列中插入元素t |
成員變量 | 1.private Node head :記錄首結點 2.private int N:記錄棧的元素個數(shù) 3.private Node last:記錄最后一個結點 |
public class MyQueue<T> implements Iterable<T>{
//記錄頭結點
private Node head;
// 記錄最后一個結點
private Node last;
//記錄鏈表的長度
private int N;
public MyQueue(){
this.head = new Node(null,null);
this.last = null;
this.N = 0;
}
/**
* 定義節(jié)點類
*/
public class Node{
T item ; //存儲數(shù)據(jù)
Node next; //下一個節(jié)點
public Node(T item, Node next) {
this.item = item;
this.next = next;
}
}
public void clear(){
this.head = null;
this.N = 0;
}
public boolean isEmpty(){
return this.N == 0;
}
public int size(){
return this.N;
}
public T get(){
if(isEmpty()){
System.out.println("沒有數(shù)據(jù)了");
return null;
}
Node n = this.head.next;
this.head.next = n.next;
N --;
if(isEmpty()){
this.head.next=null;
this.last = null;
}
return n.item;
}
public void push(T t){
if(this.head.next == null){
last = new Node(t, null);
head.next = last;
}else {
Node oldlast = last;
last = new Node(t,null);
oldlast.next = last;
}
N ++;
}
@Override
public Iterator<T> iterator() {
return new MyIterator();
}
private class MyIterator implements Iterator<T>{
Node n = head;
@Override
public boolean hasNext() {
return n.next!=null;
}
@Override
public T next() {
n = n.next;
return n.item;
}
}
}