【数据结构】栈-数组的实现

首先是定义栈的基本结构,因为用数组实现

	private String[] stack;
	private int TOP = 0;

然后是构造方法
	StackOfStrings(int capacity) {
		stack = new String[capacity];
	}

然后是push,注意,TOP永远指向的是压入元素的后一位。
	public void push(String str) {
		if (TOP == stack.length) // if full,increase the stack size
			resize(2 * stack.length);
		stack[TOP++] = str;
	}

然后是pop
	public String pop() {
		String popItem = stack[--TOP];
		// if equal to 1/4,decrease the stack size
		if (TOP > 0 && TOP == stack.length / 4)
			resize(stack.length / 2);
		return popItem;
	}


然后是判空操作,想想为什么空的时候 TOP是0
	public boolean isEmpty() {
		return TOP == 0;
	}

最后附上resize的代码
	public void resize(int capacity) {
		String[] temp = new String[capacity];
		for (int i = 0; i < TOP; i++)
			temp[i] = stack[i];
		stack = temp;
	}

相关文章

【啊哈!算法】算法3:最常用的排序——快速排序       ...
匿名组 这里可能用到几个不同的分组构造。通过括号内围绕的正...
选择排序:从数组的起始位置处开始,把第一个元素与数组中其...
public struct Pqitem { public int priority; ...
在编写正则表达式的时候,经常会向要向正则表达式添加数量型...
来自:http://blog.csdn.net/morewindows/article/details/6...