一、簡介
1.1 概念
隊列簡稱隊
–他同堆棧一樣,也是一種運算受限的線性表,其限制是僅允許在表的一端進行插入,而在表的另一端進行刪除;
在隊列中把插入數據元素的一端稱爲隊尾,刪除數據元素的一端稱爲隊頭
;
向隊尾插入元素稱爲進隊和入隊,新元素入隊後成爲新的隊尾元素;從隊列中刪除元素稱爲離隊或出隊,元素出隊後,其後續元素成爲新的隊頭元素;
由於隊列的插入和刪除操作分別在隊尾和隊頭進行,每個元素必然按照進入的次序離隊,也就是說先進隊的元素必然先離隊,所以稱隊列爲先進先出表
。
鏈式隊列
–
1.2 結構圖
二、簡單實現
public class LinkQueue implements Queue {
Node front;
Node rear;
int count;
public LinkQueue() {
init();
}
public void init() {
front = rear = null;
count = 0;
}
public void append(Object obj) throws Exception {
Node node = new Node(obj, null);
if (rear != null) {
rear.next = node;
}
rear = node;
if (front == null) {
front = node;
}
count++;
}
public Object delete() throws Exception {
if (isEmpty()) {
new Exception("隊列已空!");
}
Node node = front;
front = front.next;
count--;
return node.getElement();
}
public Object getFront() throws Exception {
if (!isEmpty()) {
return front.getElement();
} else {
return null;
}
}
public boolean isEmpty() {
return count == 0;
}
}
public class Node {
Object element;
Node next;
public Node(Node nextval) {
this.next = nextval;
}
public Node(Object obj, Node nextval) {
this.element = obj;
this.next = nextval;
}
public Node getNext() {
return this.next;
}
public Object getElement() {
return this.element;
}
public void setNext(Node nextval) {
this.next = nextval;
}
public void setElement(Object obj) {
this.element = obj;
}
public String toString() {
return this.element.toString();
}
}