码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-11-06 02:07:02      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:blog   java   for   数据   2014   log   代码   amp   size   

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

	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;
	}




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

标签:blog   java   for   数据   2014   log   代码   amp   size   

原文地址:http://blog.csdn.net/yexiao123098/article/details/40840973

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!