栈是一种特殊的线性表,插入和删除操作只能在一端进行,这个端叫做栈顶,另一个端叫栈底。栈也可用顺序存储和链式存储实现
栈的基本操作如下
public interface IStack
{
public void clear(); //置空
public boolean isEmpty(); //判空
public int length(); //求长度
public Object peek(); //取栈顶元素
public void push(Object x); //入栈
public Object pop(); //出栈
}
顺序存储实现如下
public class SqStack implements IStack
{
private Object[] stackElem;
private int top; //top指向栈顶元素存储位置的下一个存储单元
public SqStack(int maxSize)
{
top = 0;
stackElem = new Object[maxSize];
}
@Override
public void clear() {
top = 0;
}
@Override
public boolean isEmpty() {
return top == 0;
}
@Override
public int length() {
return top;
}
@Override
public Object peek() {
//首先要判断栈是否为空(有无元素可取)
if(!isEmpty())
{
return stackElem[top-1];
}else
return null;
}
@Override
public void push(Object x) throws Exception {
//进栈前要判断栈是否已满(是否有地方进来)
if(top == stackElem.length)
throw new Exception("栈已满");
else
stackElem[top++] = x; //进栈后栈顶指针要加1
}
@Override
public Object pop() {
//要判断栈是否为空(是否有元素可出来)
if(isEmpty())
return null;
else
return stackElem[--top]; //出栈后栈顶元素减1
}
public void display()
{
for(int i=top-1;i>=0;i--)
{
System.out.println(stackElem[i].toString()+" ");
}
}
}
链栈实现如下
public class LinkStack implements IStack
{
//链栈采用不带头节点的单链表来实现,top指向栈顶元素
private Node top;
@Override
public void clear() {
top = null;
}
@Override
public boolean isEmpty() {
return top == null;
}
@Override
public int length() {
Node p = top;
int length = 0;
while(p!=null)
{
p = p.getNext();
length++;
}
return length;
}
@Override
public Object peek() {
if(!isEmpty())
return top.getData();
else
return null;
}
@Override
public void push(Object x) throws Exception {
Node p = new Node(x);
p.setNext(top);
top = p;
}
@Override
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();
}
}
}