mirror of
https://git.adityakumar.xyz/data-structures.git
synced 2024-12-22 19:52:52 +00:00
add linked list stack
This commit is contained in:
parent
280f26762e
commit
9f630e7b14
1 changed files with 38 additions and 0 deletions
38
stack/LStack.java
Normal file
38
stack/LStack.java
Normal file
|
@ -0,0 +1,38 @@
|
||||||
|
/** Linked stack implementation */
|
||||||
|
class LStack<E> implements Stack<E> {
|
||||||
|
private Link<E> 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<E>(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; }
|
||||||
|
}
|
Loading…
Reference in a new issue