IStack
package Stack;
public interface IStack {
public void clear();
public boolean isEmpty();
public int length();
public Object peek();
public void push(Object x) throws Exception;
public Object pop();
public void display();
}
SqStack
package Stack;
public class SqStack implements IStack {
private Object[] stackElem;
private int top;
public SqStack(int maxSize) {
top = 0;
stackElem = new Object[maxSize];
}
public void clear() {
top = 0;
}
public boolean isEmpty() {
return top == 0;
}
public int length() {
return top;
}
/**
* @description 取栈顶元素
* @return
* @time 2015年12月23日 上午12:10:15
*/
public Object peek() {
if (!isEmpty()) {
return stackElem[top - 1];
} else
return null;
}
/**
* @description 入栈
* @param x
* @throws Exception
* @time 2015年12月23日 上午12:11:59
*/
public void push(Object x) throws Exception {
if (top == stackElem.length)
throw new Exception("栈已满");
else
stackElem[top++] = x;
}
/**
* @description 出栈
* @return
* @time 2015年12月23日 上午12:12:09
*/
public Object pop() {
if (isEmpty())
return null;
else
return stackElem[--top];
}
public void display() {
for (int i = top - 1; i >= 0; i--) {
System.out.println(stackElem[i].toString());
}
}
}
Node
package Stack;
class Node {
private Object data;
private Node next;
public Node() {
this(null);
}
public Node(Object data) {
this.data = data;
this.next = null;
}
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;
}
}
LinkStack
public class LinkStack implements IStack {
private Node top;
public void clear() {
top = null;
}
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;
}
/**
* @description 入栈
* @param x
* @time 2015年12月23日 上午12:19:39
*/
public void push(Object x) {
Node p = new Node(x);
p.setNext(top);
top = p;
}
/**
* @description 出栈
* @return
* @time 2015年12月23日 上午12:19:48
*/
public Object pop() {
if (isEmpty())
return null;
else {
Node p = top;
top = top.getNext();
return p.getData();
}
}
public void display() {
Node p = top;
while (p != null) {
System.out.println(p.getData().toString() + " ");
p = p.getNext();
}
}
}