栈的实现(分别用数组和链表的java实现)


/**
 * 文件名:StackText.java
 * 时间:2014年10月21日下午8:43:02
 * 作者:修维康
 */
package chapter3;

/**
 * 类名:StackText 说明:用链表和数组分别实现栈;
 */
class ArrayStack<AnyType> {
	public static final int DEFAULT_CAPACITY = 10;
	private AnyType[] theArray;
	private int topOfStack;
	private int size;

	public ArrayStack() {
		clear();
		topOfStack = -1;
	}

	public void push(AnyType x) {
		if (size == theArray.length)
			ensureCapacity(2 * size + 1);
		theArray[++topOfStack] = x;
		size++;
	}

	public AnyType top() {
		if (topOfStack != -1)
			return theArray[topOfStack];
		return null;
	}

	public AnyType pop() {
		if (topOfStack != -1)
			size--;
		return theArray[topOfStack--];
	}

	public void clear() {
		topOfStack = -1;
		ensureCapacity(DEFAULT_CAPACITY);
	}

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

	public void ensureCapacity(int newCapacity) {
		if (newCapacity < size)
			return;
		AnyType[] old = theArray;
		theArray = (AnyType[]) new Object[newCapacity];
		for (int i = 0; i < size; i++)
			theArray[i] = old[i];
	}
}

/**
 * 类名:LinkedStack 说明:链表实现栈
 */
class LinkedStack<AnyType> {
	private static class Node<AnyType> {
		Node(AnyType data, Node<AnyType> prev) {
			this.data = data;
			this.prev = prev;
		}

		private AnyType data;
		private Node<AnyType> prev;
	}

	private Node<AnyType> bottom;

	public LinkedStack() {
		clear();
	}

	public void clear() {
		bottom = new Node<AnyType>(null, null);
	}

	public void push(AnyType x) {
		bottom = new Node<AnyType>(x, bottom);
	}

	public AnyType top() {
		if (bottom != null)
			return bottom.data;
		return null;
	}

	public AnyType pop() {
		if (bottom != null) {
			bottom = bottom.prev;
			return bottom.data;
		}
		return null;
	}

	public boolean isEmpty() {
		return bottom.prev == null;
	}
}

public class StackTest {

	/**
	 * 方法名:StackText.java 说明:测试
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		ArrayStack stack1 = new ArrayStack();
		for (int i = 1; i < 100; i++)
			stack1.push(i);
		// stack1.clear();
		System.out.println(stack1.top());
		while (!stack1.isEmpty())
			System.out.println(stack1.pop());

		ArrayStack stack2 = new ArrayStack();
		stack2.push(1);
		stack2.push(2);
		stack2.push(3);
		stack2.push(4);
		// stack2.clear();
		System.out.println(stack2.top());
		while (!stack2.isEmpty())
			System.out.println(stack2.pop());
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值