java 打印栈回溯_数据结构(java):使用栈的回溯机制,设计并实现八皇后问题,至少得到一个解...

给出顺序栈和链栈的源代码,求大大们帮帮忙顺序栈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();

}

}

展开

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值