欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > > 文章正文

Java用ArrayList实现栈,javaarraylist实现

来源: javaer 分享于  点击 8201 次 点评:235

Java用ArrayList实现栈,javaarraylist实现



import java.util.ArrayList;

/**
 * 使用Java的ArrayList集合构造顺序栈
 * @author Administrator
 *		包含参数:	elements 栈元素
 *				length	   栈实际长度
 *		包含方法:	Stack()			构造栈
 *				clearStack()	清空栈
 *				isEmpty()		判断栈空
 *				getLength()		返回栈长
 *				getTop()		返回栈顶元素
 *				push(T ele)		元素进栈
 *				pop()			元素出栈
 */
public class Stack {
	ArrayList elements;
	int length;
	/**
	 * Constructor
	 */
	public Stack () {
		elements = new ArrayList();
		length = 0;
	}
	/**
	 * Clear the Stack
	 */
	public void clearStack() {
		for(int i=elements.size()-1;i>=0;i--) {
			elements.remove(i);
		}
		length = 0;
	}
	/**
	 * if the Stack is Empty, return true , else return false
	 * @return	empty result
	 */
	public boolean isEmpty() {
		if(elements == null) {
			return true;
		}
		if(length == 0) {
			return true; 
		}
		return false;
	}
	/**
	 * get the Stack length
	 * @return length
	 */
	public int getLength() {
		return length;
	}
	/**
	 * get the top element of the stack. 
	 * if exists, return true and give the value to T, else, return false
	 * @param temp	top element of the stack
	 */
	public T getTop() {
		if(elements == null && length == 0) {
			return null;
		} else {
			T temp = elements.get(length-1);
			return temp;
		}
	}
	/**
	 * push a element(type T) to the stack
	 * @param ele
	 */
	public void push(T ele) {
		length++;
		elements.add(ele);
	}
	/**
	 * pop a element(type T) from the stack
	 * @param ele
	 */
	public T pop() {
		T temp = elements.get(length-1);
		elements.remove(length-1);
		length--;
		return temp;
	}
}

相关文章

    暂无相关文章

用户点评