|
|
|
@ -8,7 +8,7 @@ public class LinkedNumberStack implements NumberStack |
|
|
|
|
|
|
|
// check whether the stack is empty |
|
|
|
public boolean isEmpty() |
|
|
|
{ |
|
|
|
{ |
|
|
|
if (m_top == null) |
|
|
|
return true; |
|
|
|
else |
|
|
|
@ -20,10 +20,10 @@ public class LinkedNumberStack implements NumberStack |
|
|
|
{ |
|
|
|
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 |
|
|
|
@ -33,38 +33,54 @@ public class LinkedNumberStack implements NumberStack |
|
|
|
// push a value onto the stack |
|
|
|
public void push(int v) |
|
|
|
{ |
|
|
|
// TODO: implement this method |
|
|
|
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() |
|
|
|
{ |
|
|
|
// TODO: implement this method |
|
|
|
|
|
|
|
return -1; // replace this statement with your own return |
|
|
|
{ |
|
|
|
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() |
|
|
|
{ |
|
|
|
// TODO: implement this method |
|
|
|
|
|
|
|
return -1; // replace this statement with your own return |
|
|
|
{ |
|
|
|
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 |
|
|
|
@Override |
|
|
|
public String toString() |
|
|
|
{ |
|
|
|
String stackContent = ""; |
|
|
|
LNode current = m_top; |
|
|
|
|
|
|
|
while (current != null) |
|
|
|
{ |
|
|
|
stackContent += current.getInfo() + " "; |
|
|
|
current = current.getLink(); |
|
|
|
} |
|
|
|
{ |
|
|
|
stackContent += current.getInfo() + " "; |
|
|
|
current = current.getLink(); |
|
|
|
} |
|
|
|
|
|
|
|
return stackContent; |
|
|
|
return stackContent; |
|
|
|
} |
|
|
|
} |
|
|
|
} |