⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 arraystack.java~5~

📁 源程序(包括最初的版本
💻 JAVA~5~
字号:
package stack;

/**

 */
import java.util.*;
public class ArrayStack implements Stack {
    //data members
    int top;// the current top of stack
    Object []stack; //element array

    //constructors
    public ArrayStack(int initialCapacity) {
        if(initialCapacity<1)
            throw new IllegalArgumentException
                  ("initialCapacity must be >=1");
        stack=new Object[initialCapacity];
        top=-1;
    }
    public ArrayStack() {
        this(10);
    }

    public boolean empty() {
        return top==-1;
    }
    public Object peek(){
        if(empty())
            throw new EmptyStackException();
        return stack[top];
    }

    // 内部方法,用新长度newLength进行栈空间的扩容
      Object []  ChangeArrayLength(Object [] element, int newLength)
      {
        // 以希望的长度及同样的类型分配数组空间
        Object [] newArray = new Object [newLength];

        // 老空间元素到新空间的拷贝
        for(int i=0;i<element.length;i++)
            newArray[i]=element[i];

        // 返回新空间
        return newArray;
      }

    public void push(Object theElement) {
        if(top==stack.length-1)
            stack=ChangeArrayLength(stack,2*stack.length);
        stack[++top]=theElement;
    }

    public Object pop() {
        if(empty())
            throw new EmptyStackException();
        Object topElement=stack[top];
        stack[top--]=null;
        return topElement;
    }

    //测试类
    public static void main(String args[]){
        //构造一个栈,初始为十个空间
        ArrayStack element=new ArrayStack();

        //判断栈空
        if(element.empty()==true) {
            System.out.println("the stack is empty");
        }

        //入栈
        element.push(new Integer(1));
        element.push(new Integer(2));
        element.push(new Integer(3));
        System.out.println("the stack is "+element);

        //获得栈顶元素
        System.out.println("the top is "+element.peek());

        //出栈
        System.out.println("the out  is "+element.pop());
        System.out.println("now the top is "+element.peek());
    }
}



⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -