1

我已经获得了一个LinkedStack.java具有属性Node rootint 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;
    }
}
4

1 回答 1

0

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

否则调用递归private size方法。如果您的当前在 next 上Node有 nextNode调用size方法Node并将变量递增size一。如果没有 next 则Node返回 counted 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;
    }
于 2021-11-06T13:12:24.297 回答