其他分享
首页 > 其他分享> > 数组实现栈_压入/弹出_20210321

数组实现栈_压入/弹出_20210321

作者:互联网

package per.zhangyh.algorithm;

/**
 *@author:zhangyonghui;
 *@date: 2021/3/21; 20:28
 *@Describe:
 */
public class MyStackTest {
    public static void main(String[] args) {
        MyStack myStack = new MyStack();

        //压入元素:
        myStack.push(2);
        myStack.push(3);
        myStack.push(5);
        myStack.push(55);
        myStack.push(10);
        myStack.push(100);
        myStack.push(1770);

        //弹出元素:
        myStack.pop();
        myStack.pop();
        myStack.pop();

        //查看栈顶元素:
        System.out.println("栈顶元素: " + myStack.peek());
    }


}

//数组实现栈;压入元素,弹出元素;
class MyStack {
    //先初始化一个数组:
    int[] arrays = new int[0];

    /**
     *  压入一个元素:
     */
    public int[] push(int a) {
        //复制数组,长度加一:
        int[] tempArrays = new int[arrays.length + 1];

        //复制数据:
        for (int i = 0; i < arrays.length; i++) {
            tempArrays[i] = arrays[i];
        }

        //压入元素:
        tempArrays[arrays.length] = a;

        //替换原数组:
        arrays = tempArrays;

        //返回数据:
        return arrays;
    }


    /**
     * 弹出一个元素:
     */
    public int pop() {
        //避免空栈弹出数据,导致出现栈下溢异常:
        if (arrays.length == 0) {
            throw new RuntimeException("栈已经空了,不能再弹出数据!");
        }

        //复制数组,长度减一:
        int[] tempArrays = new int[arrays.length - 1];

        //复制数据:
        for (int i = 0; i < arrays.length - 1; i++) {
            tempArrays[i] = arrays[i];
        }

        //替换原数组:
        arrays = tempArrays;

        //返回弹出的元素:
        return arrays[arrays.length - 1];
    }

    /**
     * 查看栈顶元素:
     */
    public int peek() {
        return arrays[arrays.length - 1];
    }


}

 

标签:压入,arrays,20210321,int,length,弹出,tempArrays,push,myStack
来源: https://blog.csdn.net/qq_44750696/article/details/115055753