栈的作用,用于创建栈的解决方案仍保持不变在上一篇博客中,我用数组来创建了ArrayStack< T >类来实现栈,但也可以该用其他任何有效的栈实现、除了类名之外不用改变其他任何东西。这正是抽象的美妙之处。
只要有效地实现了恰当的操作,集合的任何实现都可用来求解问题
定义结点对象
package 数据结构;
public class LinkedNode<T> {
private T element;
private LinkedNode<T> next;
//构造方法一
public LinkedNode() {
next = null;
element = null;
}
//构造方法二
public LinkedNode(T element) {
this.element = element;
}
public void setNext(LinkedNode<T> next) {
this.next = next;
}
public LinkedNode<T> getNext() {
return next;
}
public T getElement() {
return element;
}
public void setElement(T element) {
this.element = element;
}
}
定义接口
package 数据结构;
public interface StackADT<T> {
//压栈方法
public void push(T element);
//弹栈方法
public T pop();
//查看栈顶元素方法
public T peek();
//栈判空方法
public boolean isEmpty();
}
接口实现类
package 数据结构;
public class LinkedStack<T> implements StackADT<T> {
private int count;
private LinkedNode<T> top;
public LinkedStack() {
count = 0;
top = null;
}
//压栈方法
@Override
public void push(T element) {
LinkedNode<T> temp = new LinkedNode<T> (element);
temp.setNext(top);
top = temp;
count++;
}
//弹栈方法
@Override
public T pop() throws EmptyCollectionException{
if (isEmpty())
throw new EmptyCollectionException("Stack");
T temp = top.getElement();
top = top.getNext();
count--;
return temp;
}
//查看栈顶元素方法
@Override
public T peek() throws EmptyCollectionException{
if (isEmpty())
throw new EmptyCollectionException("Stack");
T temp = top.getElement();
return temp;
}
//栈判空方法
@Override
public boolean isEmpty() {
if (count <= 0)
return true;
else
return false;
}
}
//新建异常类
class EmptyCollectionException extends RuntimeException{
public EmptyCollectionException(String collection) {
super("The "+collection+" is empty.");
}
}