给出顺序栈和链栈的源代码,求大大们帮帮忙顺序栈SqStack.javapackagedataStructure.linearList;publicclassSqStackimplementsIStack{privateE[]stackElem;privateinttop;//构造...
给出顺序栈和链栈的源代码,求大大们帮帮忙
顺序栈SqStack.java
package dataStructure.linearList;
public class SqStack implements IStack {
private E[] stackElem;
private int top;
//构造一个容量为maxSize的空栈
public SqStack (int maxSize) {
stackElem = (E[]) new Object[maxSize];
top = 0;
}
// 栈置空
public void clear( ) {
top= 0;
}
// 栈判空
public boolean isEmpty( ) {
return top== 0;
}
// 求栈数据元素个数函数
public int length( ) {
return top;
}
// 取栈顶元素的函数
public E peek ( ) {
if (!isEmpty()) // 栈非空
return stackElem[top-1]; // 栈顶元素
else
return null;
}
//入栈
public void push (E x) throws Exception {
if (top == stackElem.length)
throw new Exception("栈已满");
else
stackElem[top++] = x;
}
//出栈
public E 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());
}
}
链栈LinkStack.java
package dataStructure.linearList;
public class LinkStack implements IStack {
private Node top;
private int curLen;
public LinkStack(){
top = null;
curLen = 0;
}
// 栈置空
public void clear( ) {
top = null;
curLen = 0;
}
// 栈判空
public boolean isEmpty( ) {
return top== null;
}
// 求栈数据元素个数函数
public int length( ) {
return curLen;
}
// 取栈顶元素的函数
public E peek ( ) {
if (!isEmpty()) // 栈非空
return top.getData( ); // 栈顶元素
else
return null; //栈空
}
//入栈
public void push (E x) throws Exception {
Node p = new Node(x);
if (p == null)// 内存空间不够
throw new Exception("链表已满");
p.setNext(top);
top = p;
curLen++;
}
//出栈
public E pop () {
if (isEmpty())
return null;
Node p = top;
top=top.getNext( );
curLen--;
return p.getData( );
}
// 输出函数(从栈顶到栈底)
public void display () {
Node p = top;
while (p != null) {
System.out.println(p.getData( ));
p = p.getNext(); // 取下一个结点
}
System.out.println();
}
}
展开