Algorithm——简单数据结构之栈(十二)

Algorithm——简单数据结构之栈


栈(stack)又名堆栈,它是一种运算受限的线性表。其限制是仅允许在表的一端进行插入和删除运算。这一端被称为栈顶,相对地,把另一端称为栈底。向一个栈插入新元素又称作进栈、入栈或压栈,它是把新元素放到栈顶元素的上面,使之成为新的栈顶元素;从一个栈删除元素又称作出栈或退栈,它是把栈顶元素删除掉,使其相邻的元素成为新的栈顶元素。由此可知,栈实现的是一种后进先出的策略。

栈有三个基本操作:1、判断栈是否为空;2、元素入栈;3、元素出栈。由数组实现一个普通栈是较为简单的:设计一个栈顶指针top,指向栈中最新插入的元素;并实现栈的三个基本操作。

一个栈的Java简单实现如下所示:

/**
 * 
 * 栈实现的是一种后进先出策略
 * 
 * 栈的基本操作有:判断栈是否为空/数据入栈/数据出栈
 * 
 * @author coder
 *
 */
class Stack {

	private int[] stack;

	public Stack() {
		stack = new int[255];
	}

	private int top = -1;// 栈顶指针

	/**
	 * 栈是否为空
	 * 
	 * @return
	 */
	public boolean isEmpty() {
		if (top == -1)
			return true;
		return false;
	}

	/**
	 * 
	 * 元素入栈
	 * 
	 * @param x
	 */
	public void push(int x) {
		top++;
		stack[top] = x;
	}

	/**
	 * 
	 * 元素出栈
	 * 
	 * @return
	 */
	public int pop() {
		if (isEmpty() == true)
			throw new IllegalArgumentException("underflow...");
		else
			top--;
		return stack[top + 1];

	}

	/**
	 * 
	 * 栈元素个数
	 * 
	 * @return
	 */
	public int stackSize() {
		return (top + 1);
	}

}

完整的测试代码如下所示:

public class BaseDataStructure {

	public static void main(String[] args) {

		Stack stack = new Stack();

		System.out.println(stack.isEmpty());

		stack.push(1);
		stack.push(2);
		stack.push(3);
		stack.push(4);
		stack.push(5);

		while (!stack.isEmpty()) {
			System.out.println(stack.pop());
		}
	}
}

/**
 * 
 * 栈实现的是一种后进先出策略
 * 
 * 栈的基本操作有:判断栈是否为空/数据入栈/数据出栈
 * 
 * @author coder
 *
 */
class Stack {

	private int[] stack;

	public Stack() {
		stack = new int[255];
	}

	private int top = -1;// 栈顶指针

	/**
	 * 栈是否为空
	 * 
	 * @return
	 */
	public boolean isEmpty() {
		if (top == -1)
			return true;
		return false;
	}

	/**
	 * 
	 * 元素入栈
	 * 
	 * @param x
	 */
	public void push(int x) {
		top++;
		stack[top] = x;
	}

	/**
	 * 
	 * 元素出栈
	 * 
	 * @return
	 */
	public int pop() {
		if (isEmpty() == true)
			throw new IllegalArgumentException("underflow...");
		else
			top--;
		return stack[top + 1];

	}

	/**
	 * 
	 * 栈元素个数
	 * 
	 * @return
	 */
	public int stackSize() {
		return (top + 1);
	}

}




猜你喜欢

转载自blog.csdn.net/csdn_of_coder/article/details/80274647