Linear Data Structures_ Stacks Cheatsheet _ Codecademy
Linear Data Structures_ Stacks Cheatsheet _ Codecademy
Stacks
The .pop() method of the Java Stack class public String pop() {
removes the node at the top of the stack. It does so
if (!this.isEmpty()) {
using the LinkedList method
.removeHead() . It then decreases the stack String data =
size variable, returns the data of the removed node, this.stack.removeHead();
and throws an error if the stack is empty. The helper this.size--;
method .isEmpty() is used to verify this.
return data;
} else {
throw new Error("Stack is empty!");
}
}
A Java Stack class can implement two helper public boolean hasSpace() {
methods to determine actions that should be taken
return this.size < this.maxSize;
with the stack:
.hasSpace() returns a boolean }
representing if there is space left in a bounded
stack. It is used within the Stack public boolean isEmpty() {
.push() method.
.isEmpty() returns a boolean return this.size == 0;
representing whether the stack is empty or not. }
It is used within the Stack .pop() and
.peek() methods.
The .peek() method of the Java Stack class public String peek() {
examines, but does not remove, the top node of the
if (this.isEmpty()) {
stack. It returns the top node value if there is one, and
returns null if the stack is empty. The top node is return null;
accessed using the head attribute of the linked list } else {
stack . The top node’s data is accessed using the return this.stack.head.data;
data attribute of the head node.
}
}
A key method of the Java Stack class is public void push(String data) {
.push() . This method takes a single String
if (this.hasSpace()) {
argument, data , and adds this value to the top of the
stack using the LinkedList method this.stack.addToHead(data);
.addToHead() . It then increases the size this.size++;
variable and throws an error if the stack is full to ensure } else {
that the stack does not overflow with nodes. It verifies
throw new Error("Stack is
this using the helper method .hasSpace() .
full!");
}
}
Java Stack Behavior