`

一个简单的java栈

阅读更多
public class MyStack {
	private long[] arr;

	private int top;

	public MyStack() {
		arr = new long[10];
		top = -1;
	}

	public MyStack(int maxsize) {
		arr = new long[maxsize];
		top = -1;
	}

	// add
	public void push(int value) {
		arr[++top] = value;
	}

	// remove{
	public long pop() {
		return arr[top--];
	}

	public long peek() {
		return arr[top];
	}

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

	public boolean isFull() {
		return top == arr.length - 1;
	}

	public static void main(String[] args) {
		MyStack myStack = new MyStack(4);
		myStack.push(1);
		myStack.push(2);
		myStack.push(3);
		myStack.push(4);
		System.out.println(myStack.isEmpty());
		System.out.println(myStack.isFull());
		System.out.println(myStack.peek());
		System.out.println(myStack.peek());
		while (!myStack.isEmpty()) {
			myStack.pop();
		}
		System.out.println(myStack.isEmpty());
		System.out.println(myStack.isFull());
	}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics