我已经获得了一个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;
}
}