社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
java中常用的栈操作
top赋初值是-1,入栈先做top++,出栈先赋值后top–
如图:
示例代码:
先写一个接口类
public interface IStack {
void push(Object obj) throws Exception;
Object pop() throws Exception;
boolean isEmpty();
}
接口的实现
public class MyStack implements IStack {
private int top = -1;
private Object arrStr[] = new Object[5];
public void push(Object obj) throws Exception {
if (top >= arrStr.length - 1) {
throw new Exception("超出栈顶");
} else {
top++;
arrStr[top] = obj;
}
}
public Object pop() throws Exception {
if (top < 0) {
throw new Exception("超出栈底");
} else {
Object obj = arrStr[top];
arrStr[top]=null;
top--;
return obj;
}
}
public boolean isEmpty() {
return top == -1;
}
public void print() {
if (!isEmpty()) {
for (int i = 0; i <= top; i++) {
System.out.println(arrStr[i]);
}
} else {
System.out.println("空");
}
}
}
测试类
public class TestStack {
public static void main(String[] args) {
MyStack ms=new MyStack();
try {
ms.push(“aaa”);
ms.push(“bbb”);
ms.push(“ccc”);
ms.push(“ddd”);
ms.push(“eee”);
//ms.push(“eee”);
ms.pop();
ms.pop();
ms.pop();
//ms.pop();
//ms.pop();
System.out.println(ms.isEmpty());
ms.print();
} catch (Exception e) {
e.printStackTrace();
}
}
}
“`
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!