From 7c14f942be47dcbf20e0a17099e4f644f883b755 Mon Sep 17 00:00:00 2001 From: Raphael Roberts Date: Thu, 26 Sep 2019 18:35:42 -0500 Subject: [PATCH] Finished LinkedNumberStack --- .gitignore | 2 ++ LinkedNumberStack.java | 54 +++++++++++++++++++++++++++--------------- 2 files changed, 37 insertions(+), 19 deletions(-) diff --git a/.gitignore b/.gitignore index 773a6df..5041262 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ *.dat +*.class +/TAGS diff --git a/LinkedNumberStack.java b/LinkedNumberStack.java index 3484931..996afcc 100644 --- a/LinkedNumberStack.java +++ b/LinkedNumberStack.java @@ -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; } -} \ No newline at end of file +}