为用户定义的堆栈类

时间:2015-10-23 17:01:56

标签: stack size

我正在编写一个需要堆栈长度/大小的程序。因为我没有导入Stack类(我已经创建了自己的 - 见下文),我不知道如何创建一个计算堆栈大小并返回该整数值的方法。到目前为止,这是Stack类:

public class Stack<String> implements StackInter<String>
{
    public void push(String x)
    { // This method is written
    }
    public String pop()
    { // This method is written
    }
    public boolean isEmptyStack()
    { // This method is written
    }
    public String peek()
    { // This method is written
    }

    public int size()
    {
        // What goes in here!
    }
}

这是我想使用size方法的地方

public class InfixCalculator
{
    Stack<String> stack = new Stack<String>();
    int size = stack.size();
}

任何建议都将不胜感激!

2 个答案:

答案 0 :(得分:0)

如果你的Stack是一个数组写

public int size() {
  return array.length;
}

答案 1 :(得分:0)

伪代码是这样的:

    public class Stack<String> implements StackInter<String>
    {
        private size;
        //constructor 
        public Stack<String>(){
        size=0;

        }
        public void push(String x)
        { // This method is written
          size++;
        }
        public String pop()
        { // This method is written
          if(size > 0 )
            size--;
        }
        public boolean isEmptyStack()
        { // This method is written
        }
        public String peek()
        { // This method is written


        }

        public int size()
        {
           int theSize=size;
           return theSize;

        }
    }

应用操作后,可以计算大小。