Java中的栈操作

来源:互联网 发布:水星家纺网络 编辑:程序博客网 时间:2024/06/18 16:21

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();    }}

}

“`

0 0