public Node(Object data) {// 构造值为data的结点 this(data,null); } public Node(Object data, Node next) { this.data = data; this.next = next; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } }
2.栈接口
public interface IStack { public void clear(); // 将一个已经存在的栈置成空 public boolean isEmpty(); // 测试栈是否为空 public int length();// 求栈中的数据元素个数并由函数返回其值 public Object peek();// 查看栈顶对象而不移除它,返回栈顶对象 public Object pop();// 移除栈顶对象并作为此函数的值返回该对象 public void push(Object o) throws Exception;// 把项压入栈顶 public void display();// 打印函数,打印所有栈中的元素(栈底到栈顶) }
3.单链表实现栈
public class LinkStack implements IStack{
private Node top;// 栈顶元素的引用
//清空栈 public void clear() { top=null; } //栈数据展示 public void display() { Node p=top; int index=1; while(p!=null) { System.out.println("(节点"+index+")"+p.getData()); p=p.getNext(); index++; } }
//栈是否为空 public boolean isEmpty() { return top==null; } //栈长度 public int length() { Node p=top; int length=0; while(p!=null) { p=p.getNext(); length++; } return length; }
//取出首元素,但不删除 public Object peek() { if (!isEmpty()) return top.getData();// 返回栈顶元素 else return null; } //取出首元素,并删除 public Object pop() { if (!isEmpty()) { Node p = top;// p指向栈顶结点 top = top.getNext(); return p.getData(); } else return null; }
//插入数据 public void push(Object o) throws Exception { //改变栈顶结点 Node p = new Node(o); // 构造一个新的结点 p.setNext(top); top = p; }
public Node getTop() { return top; } public void setTop(Node top) { this.top = top; } }
4.顺序结构实现栈 public class SqStack implements IStack{ private Object[] stackElem; // 栈存储空间 private int top; // 非空栈中始终表示栈顶元素的下一个位置,当栈为空时其值为0
public SqStack(int maxSize) { stackElem=new Object[maxSize]; top=0; }
//清空栈 public void clear() { top=0; }
//展示队列 public void display() { //从站栈顶开始打印 for (int i=top-1;i>=0;i--) { System.out.println(stackElem.toString()
+ " ");// 打印
}
}