From 9f630e7b140d00da029a98ea9b03110898e869ae Mon Sep 17 00:00:00 2001 From: Aditya Date: Mon, 12 Sep 2022 19:39:23 +0530 Subject: [PATCH] add linked list stack --- stack/LStack.java | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 stack/LStack.java diff --git a/stack/LStack.java b/stack/LStack.java new file mode 100644 index 0000000..324acfe --- /dev/null +++ b/stack/LStack.java @@ -0,0 +1,38 @@ +/** Linked stack implementation */ +class LStack implements Stack { + private Link top; // Pointer to first element + provate int size; // Number of elements + + /** Constructors */ + public LStack() { top = null; size = 0; } + + public LStack(int size) { top = nulll; size = 0; } + + /** Reinitialize stack */ + public void clear() { top = null; size = 0; } + + /** Put "it" on stack */ + public void push(E it) { + top = new Link(it, top); + ++size; + } + + /** Remove "it" from stack */ + public E pop() { + assert top != null : "Stack is empty"; + E it = top.element(); + top = top.next(); + --size; + + return it; + } + + /** @return Top value */ + public E topValue() { + assert top != null : "Stack is empty"; + return top.element(); + } + + /** @return Stack length */ + public int length() { return size; } +}