1. 程式人生 > >資料結構(棧與佇列) java實現

資料結構(棧與佇列) java實現

  • 棧的相關定義
package StackDef;

import java.util.Arrays;
import java.util.EmptyStackException;

/**
 * 通過陣列模擬棧
 * @author tian
 *
 */
public class ArrayStack {
	private Object[] elementData;
	
	private int top;
	
	private int size;
	
	public int getTop() {
		return top;
	}

	public void setTop(int top) {
		this.top = top;
	}

	public int getSize() {
		return size;
	}

	public void setSize(int size) {
		this.size = size;
	}

	/**
	 * 預設構造一個容量為10的棧
	 */
	public ArrayStack(){
		this.elementData = new Object[10];
		this.top = -1;
		this.size = 10;
	}
	
	public ArrayStack(int initSize){
		if (initSize <0) {
			throw new IllegalArgumentException("棧的初始容量不能為0");
		}
		
		this.elementData = new Object[initSize];
		this.top = -1;
		this.size = initSize;
	}
	
	
	public Object push(Object obj){
		isGrow(top+1);
		elementData[++top] = obj;
		return obj;
	}
	
	public Object pop(){
		if (this.top == -1) {
			throw new EmptyStackException();
		}
		Object obj = elementData[top];
		elementData[top]=null;
		this.top --;
		return obj;
	}
	
	public boolean isEmpty(){
		return top ==-1;
	}
	
	
	
	public boolean isGrow(int minSize){
		int oldSize = size;
		if (minSize >= oldSize) {
			int newSize = 0;
			if ((oldSize<<1) - Integer.MAX_VALUE >0) {
				newSize = Integer.MAX_VALUE;
			} else {
				newSize = (oldSize <<1);
			}
			
			this.size = newSize;
			elementData = Arrays.copyOf(elementData, size);
			return true;
			
		} else {
			return false;
		}
	}
	
	
}
  • 兩個棧構成一個佇列
public class Queue {
	
	private ArrayStack stack1;
	private ArrayStack stack2;
	
	public Queue() {
		stack1 = new ArrayStack(10);
		stack2 = new ArrayStack(10);
	}
	
	public Object pop() throws Exception{
		if (stack2.getTop()==-1) {
			while (stack1.getTop() !=-1) {
				Object obj = stack1.pop();
				stack2.push(obj);
			}
		}
		
		if (stack2.getTop() == -1) {
			throw new Exception("queue is empty");
		}
		return stack2.pop();
		
	}
	
	public Object push(Object obj){
		return stack1.push(obj);
	}
	
	public static void main(String[] args) throws Exception {
		Queue queue = new Queue();
		queue.push(1);
		queue.push(2);
		queue.push(3);
		queue.push(4);
		queue.push(5);
		
		System.out.println(queue.pop());
		System.out.println(queue.pop());
		System.out.println(queue.pop());
		System.out.println(queue.pop());
		System.out.println(queue.pop());
		System.out.println(queue.pop());
	}
}