zoukankan      html  css  js  c++  java
  • 用数组实现栈

    用数组实现栈,设置三个属性
    1、maxSize 用来记录这个数组实现的栈能存放多少个数据
    2、long[] stackArray 定义一个数组栈
    3、top 记录栈顶
    方法有
    1、有参构造函数,创建一个栈,参数是栈的大小
    2、push方法,压入一个数字
    3、pop方法,弹出栈顶的一个数字
    4、peek方法,查看栈顶的数字
    5、isEmpty(),isFull()判断是不是空的栈和栈满了没有
    /**
     * Description:用数组实现栈
     * @author 李弘昊2019年10月29日 
     */
    class StackX
    {
        private int maxSize;        //size of stack array
        private long[] stackArray;
        private int top;            //top of stack
        
        public StackX(int s)        //constructor
        {
            maxSize = s;
            stackArray = new long[maxSize]; //create array
            top = -1;                //no items yet
        }
        
        public void push(long j)    //put item on top of stack
        {
            stackArray[++top] = j;    //increment top,insert item
        }
    
        public long pop()            //take item from top of stack
        {
            return stackArray[top--];//access items,decrement top
        }
        
        public long peek()            //peek at top of stack
        {
            return stackArray[top];
        }
        
        public boolean isEmpty()    //true if stack is empty
        {
            return(top == -1);
        }
        
        public boolean ifFull()        //true if stack is full
        {
            return(top == maxSize-1);
        }
        
    }
    
    public class StackApp
    {
        public static void main(String[] args)
        {
            StackX theStack = new StackX(10);    //make new stack 
            
            theStack.push(20);                    //push items onto stack
            theStack.push(40);
            theStack.push(60);
            theStack.push(80);
            
            System.out.println("the top value:"+theStack.peek());
            
            while(!theStack.isEmpty())            //until it'empty
            {
                System.out.print(theStack.pop());
                System.out.print(" ");
            }
        }
    }
    View Code

    我们用数组实现栈要先规定栈的大小,栈还可以用链表实现,用链表实现可以不先规定栈的容量。

  • 相关阅读:
    Android_1_渐变背景色
    js 数组常用方法说明
    js模拟键盘按键事件
    SqlServer中截取字符串
    SqlServer将日期格式DateTime转换成varchar类型
    如何经营好(开好)一家淘宝店铺
    如何才能学好javascript
    前端常用的正则表达式
    淘宝中的一些基本CSS代码
    CSS样式中伪类和伪类元素的区别(css中一个冒号和两个冒号的区别)
  • 原文地址:https://www.cnblogs.com/lhh666/p/11761365.html
Copyright © 2011-2022 走看看