package com.itjob.structure;

public class Stack {
	private int maxSize; // 堆栈的大小
	private int[] stackArray;
	private int top;     // 堆栈顶部指针

	public Stack(int s) {
		maxSize = s; 
		// 初始化一个数组
		stackArray = new int[maxSize];
		top = -1;
	}

	public void push(int j) {
		if (!isFull())
			stackArray[++top] = j;
		else
			return;
	}

	public int pop() {
		return stackArray[top--];
	}

	/**
	 * 得到栈顶的数据而不是出栈
	 */
	public int peek() {	
		return stackArray[top];
	}

	public boolean isEmpty() {
		return (top == -1);
	}

	public boolean isFull() {
		return (top == maxSize - 1);
	}

	public String toString() {
		StringBuffer sb = new StringBuffer();
		for (int i = top; i >= 0; i--) {
			sb.append("" + stackArray[i] + " ");
		}
		return sb.toString();
	}
	
	public static void main(String[] args) {
		// 初始化一个堆栈
		Stack stack = new Stack(10);
		stack.push(20);
		stack.push(40);
		stack.push(60);
		stack.push(80);
		System.out.println(stack);
		// 打印栈顶的数据
		System.out.println(stack.peek());
		// 将栈顶的数据出栈
		stack.pop();
		System.out.println(stack);
	}
}
