I have been given a LinkedStack.java class with properties Node root and int size.
I am to modify the methods to remove the size property altogether and have every method do exactly as instructed. I've figured out how to modify all methods to remove the size property and still work properly except for the size() method. Could someone maybe point me in the right direction of how to go about solving this?
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 + "]";
}
Also here is the Node class if needed.
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;
}
}