You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
86 lines
1.8 KiB
86 lines
1.8 KiB
// The linked list based implementation for the NumberStack ADT
|
|
// Your name here
|
|
|
|
public class LinkedNumberStack implements NumberStack
|
|
{
|
|
// instance variable
|
|
private LNode m_top;
|
|
|
|
// check whether the stack is empty
|
|
public boolean isEmpty()
|
|
{
|
|
if (m_top == null)
|
|
return true;
|
|
else
|
|
return false;
|
|
}
|
|
|
|
// check whether the stack is full
|
|
public boolean isFull()
|
|
{
|
|
return false;
|
|
}
|
|
|
|
// return the element at the top of the stack
|
|
public int top()
|
|
{
|
|
if (isEmpty())
|
|
throw new RuntimeException("top attempted on an empty stack");
|
|
else
|
|
return m_top.getInfo();
|
|
}
|
|
|
|
// push a value onto the stack
|
|
public void push(int v)
|
|
{
|
|
LNode new_node = new LNode(v);
|
|
if (isEmpty()) {
|
|
m_top = new_node;
|
|
}
|
|
else {
|
|
new_node.setLink(m_top);
|
|
m_top = new_node;
|
|
}
|
|
}
|
|
|
|
// remove and return the value at the top of the stack
|
|
public int pop()
|
|
{
|
|
if (isEmpty())
|
|
throw new RuntimeException("pop attempted on an empty stack");
|
|
else {
|
|
int top_val = m_top.getInfo();
|
|
LNode prev_node = m_top.getLink();
|
|
m_top = prev_node;
|
|
return top_val;
|
|
}
|
|
}
|
|
|
|
// return the number of elements on the stack
|
|
public int size()
|
|
{
|
|
int current_size = 0;
|
|
LNode current_node = m_top;
|
|
while (current_node != null) {
|
|
current_node = current_node.getLink();
|
|
current_size += 1;
|
|
}
|
|
return current_size;
|
|
}
|
|
|
|
// return a string representation of the stack
|
|
@Override
|
|
public String toString()
|
|
{
|
|
String stackContent = "";
|
|
LNode current = m_top;
|
|
|
|
while (current != null)
|
|
{
|
|
stackContent += current.getInfo() + " ";
|
|
current = current.getLink();
|
|
}
|
|
|
|
return stackContent;
|
|
}
|
|
}
|