arraystack.java

来自「this how we make stack and queue in java」· Java 代码 · 共 50 行

JAVA
50
字号
package stackqueue;

public class ArrayStack{

	public ArrayStack(){
		theArray = (int[]) new int[DEFAULT_CAPACITY];
		topOfStack = -1;
	}
	
	public boolean isEmpty(){
		return topOfStack == -1;
	}
	public void makeEmpty(){
			topOfStack = -1;
	}
	public int top() throws UnderflowException{
		if(isEmpty())
			throw new UnderflowException("ArrayStack top.");
		return theArray[topOfStack];
	}
	public void pop() throws UnderflowException{
		if(isEmpty())
			throw new UnderflowException("ArrayStack pop.");
		topOfStack--;
	}
	public int topAndPop() throws UnderflowException{
		if(isEmpty())
			throw new UnderflowException("ArrayStack topAndPop.");
		return theArray[topOfStack--];
	}
	public void push(int x){
		if(topOfStack + 1 == theArray.length)
			doubleArray();
		theArray[++topOfStack] = x;
	}
	
	private void doubleArray(){
		int[] oldArray = theArray;
		this.theArray = new int[this.theArray.length * 2];
		for(int i = 0; i < oldArray.length; i++){
			this.theArray[i] = oldArray[i];
		}
	}
	
	private int[] theArray;
	private int topOfStack;
	
	private static final int DEFAULT_CAPACITY = 10;

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?