【问题标题】:Using root to modify the size() method of a linkedStack class java使用root修改linkedStack类java的size()方法
【发布时间】:2021-12-19 01:52:38
【问题描述】:

我获得了一个 LinkedStack.java 类,其属性为 Node root 和 int size。

我将修改方法以完全删除 size 属性,并让每个方法都完全按照指示进行。我已经想出了如何修改所有方法以删除 size 属性并且仍然可以正常工作,除了size() 方法。有人可以为我指出如何解决这个问题的正确方向吗?

public class LinkedStack implements Stack
{
    private Node root;
    private int size;

    public LinkedStack()
    {
        root = null;
    }

    public void push(Object o)
    {
        Node n = new Node(o, root);
        root = n;
    }

    public Object pop()
    {
        if(root==null)
            throw new RuntimeException("Can't pop from empty stack");

        Object result = root.getValue();
        root = root.getNext();
        return result;
    }

    public Object peek()
    {
        if(root==null)
            throw new RuntimeException("Can't peek at empty stack");

        return root.getValue();
    }

    public int size()
    {
        return size;
    }

    public boolean isEmpty()
    {
        return root==null;
    }

    public String toString()
    {
        String str = "(top) [ ";
        Node n = root;
        while(n!=null)
        {
            str += n.getValue() + " ";
            n = n.getNext();
        }
        return str + "]";
    }

如果需要,这里还有 Node 类。

public class Node
{
    private Object element;
    private Node next;

    public Node(Object o)
    {
        element = o;
    }

    public Node(Object o, Node n)
    {
        element = o;
        next = n;
    }

    public Object getValue()
    {
        return element;
    }

    public Node getNext()
    {
        return next;
    }

    public void setNext(Node n)
    {
        next = n;
    }
}

【问题讨论】:

    标签: java stack


    【解决方案1】:

    您可以使用递归实现size 方法。 如果root 是null(堆栈为空)返回0。

    否则调用递归privatesize方法。如果您当前的Node 有下一个Node 调用size 方法上的下一个Node 并将size 变量加一。如果没有下一个Node,则返回计数的size。

        public int size() {
            return root != null
                    ? size(root, 1)
                    : 0;
        }
    
        private int size(Node node, int size) {
            Node next = node.getNext();
            return next != null
                    ? size(next, size + 1)
                    : size;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-15
      • 1970-01-01
      • 1970-01-01
      • 2018-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多