Posted on 2017-03-28 15:48
為自己代言 閱讀(390)
評論(0) 編輯 收藏 所屬分類:
算法/數(shù)據(jù)結(jié)構(gòu)
package stacktest;
/**
* @Author: zzz
* @CreateTime: 2017/3/28 10:52
* @Description: 隊(duì)列特點(diǎn)(先進(jìn)先出),鏈表實(shí)現(xiàn)的隊(duì)列 在隊(duì)頭刪除元素,在隊(duì)尾插入元素。
* 這樣才能滿足隊(duì)列的特性。
*/
public class MyQueue<T> {
private Node<T> front; //隊(duì)列頭,只能刪除元素
private Node<T> rear; //隊(duì)列尾,只能用來插入入元素
private int size;//隊(duì)列的長度
/**
* 初始化隊(duì)列
*/
public MyQueue() {
front = new Node<T>();
rear = front;
}
/**
* 鏈表的數(shù)據(jù)結(jié)構(gòu)
*/
private class Node<T> {
public T data;
public Node<T> next;
public Node(T data, Node next) {
this.data = data;
this.next = next;
}
public Node(T data) {
this.data = data;
}
public Node() {
}
}
public void add(T data) {
//新插入的節(jié)點(diǎn)永遠(yuǎn)是尾節(jié)點(diǎn),它的next 指向null(即沒有后繼節(jié)點(diǎn))
Node newNode = new Node(data, null);
//讓尾節(jié)點(diǎn)next指向新節(jié)點(diǎn)
rear.next = newNode;
rear = newNode;
size++;
}
public T pop() throws Exception {
if (size < 1) {
throw new Exception("錯(cuò)誤,隊(duì)列為空。");
}
Node<T> nextNode = front.next;
front.next = nextNode.next;
size--;
if (size < 1) {
rear = front;
size = 0;
}
return nextNode.data;
}
//取隊(duì)首元素
public T peek() throws Exception {
if (size < 1){
throw new Exception("錯(cuò)誤,隊(duì)列為空。");
};
return front.next.data;
}
//返回隊(duì)列的大小
public int getSize() {
return size;
}
//判斷隊(duì)列是否為空
public boolean isEmpty() {
return size == 0;
}
/**
* 遍歷算法,移動(dòng)front指針,直到front指針追上rear指針
*/
public void traverse(){
for(Node currentNode=front.next; currentNode!=null; currentNode=currentNode.next ){
System.out.println(currentNode.data);
}
}
public static void main(String[] args)throws Exception{
MyQueue<String> queue=new MyQueue<>();
for(int i=0;i<10;i++){
queue.add("88888-"+i);
}
/* for(int i=0;i<10;i++){
String s=queue.pop();
System.out.print(s+";");
}*/
queue.traverse();
}
}