Browse Source

Finished LinkedNumberStack

master
Raphael Roberts 6 years ago
parent
commit
7c14f942be
  1. 2
      .gitignore
  2. 54
      LinkedNumberStack.java

2
.gitignore

@ -1 +1,3 @@
*.dat *.dat
*.class
/TAGS

54
LinkedNumberStack.java

@ -8,7 +8,7 @@ public class LinkedNumberStack implements NumberStack
// check whether the stack is empty // check whether the stack is empty
public boolean isEmpty() public boolean isEmpty()
{
{
if (m_top == null) if (m_top == null)
return true; return true;
else else
@ -20,10 +20,10 @@ public class LinkedNumberStack implements NumberStack
{ {
return false; return false;
} }
// return the element at the top of the stack // return the element at the top of the stack
public int top() public int top()
{
{
if (isEmpty()) if (isEmpty())
throw new RuntimeException("top attempted on an empty stack"); throw new RuntimeException("top attempted on an empty stack");
else else
@ -33,38 +33,54 @@ public class LinkedNumberStack implements NumberStack
// push a value onto the stack // push a value onto the stack
public void push(int v) 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 // remove and return the value at the top of the stack
public int pop() 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 // return the number of elements on the stack
public int size() 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 // return a string representation of the stack
@Override
@Override
public String toString() public String toString()
{ {
String stackContent = ""; String stackContent = "";
LNode current = m_top; LNode current = m_top;
while (current != null) while (current != null)
{
stackContent += current.getInfo() + " ";
current = current.getLink();
}
{
stackContent += current.getInfo() + " ";
current = current.getLink();
}
return stackContent;
return stackContent;
} }
}
}
Loading…
Cancel
Save