1. 程式人生 > >數據結構——隊列鏈表實現

數據結構——隊列鏈表實現

tac port clas struct front ron ext 鏈表實現 之一

隊列抽象數據結構之一,遵循FIFO原則,通過在初始化時構造隊首和隊尾兩個引用(指針)指向一個空節點,作為空隊列的標誌

package com.shine.test.datastruct;

import java.util.EmptyStackException;

public class LinkQueue<E> {
	
	private Node front,tail;
	class Node {
		E data;
		Node next;
	}
	
	public LinkQueue() {
		 LinkQueue<E>.Node node = new Node();
		 node.data = null;
		 node.next = null;
		 front = tail = node;
	}
	
	public boolean push(E e) {
		LinkQueue<E>.Node temp = new Node();
		temp.data = e;
		temp.next = null;
		tail.next = temp; //當加入第一個元素是應為tail和front指向同一個對象 所以此時相當於front.next =temp,但以後不是
		tail = temp;
		if(temp != null) {
			return true;
		}
		return false;
	}
	
	public E pop() {
		if(front == tail) {
			throw new EmptyStackException();
		}else {
			LinkQueue<E>.Node temp = front.next; 
			E e = temp.data;
			front.next = temp.next;
			
			if(tail == temp) { //當隊列中只有一個元素時 需要將隊列置空
				tail = front;
			}
			return e;
		}
				 
	}
	public E peek() {
		if(front == tail) {
			throw new EmptyStackException();
		}else {
			LinkQueue<E>.Node temp = front.next; 
			E e = temp.data;
			
			return e;
		}
				 
	}
}

  

數據結構——隊列鏈表實現