/**
* 文件名: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());
}
}