Skip to content

Instantly share code, notes, and snippets.

@pedrofurtado
Last active January 3, 2016 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pedrofurtado/ed3651a46e364116cc64 to your computer and use it in GitHub Desktop.
Save pedrofurtado/ed3651a46e364116cc64 to your computer and use it in GitHub Desktop.
Implementation of Stack in Java
/**
* @file
* Stack.
*
* Implementation with singly linked list, through the nested class StackNode.
* It's used nested class to improve encapsulation.
*
* @author Pedro Furtado
*/
public class Stack {
/**
* Properties of stack.
*/
private StackNode top = null;
/**
* Element of stack.
*/
class StackNode {
public int key;
public StackNode next = null;
StackNode(int key) {
this.key = key;
}
}
/**
* Push method.
*
* Add an element to the top of the stack.
*
* @param int key
* Integer key.
* @return void
*/
public void push(int key) {
StackNode node = new StackNode(key);
node.next = this.top;
this.top = node;
}
/**
* Pop method.
*
* Remove the element on the top of stack.
*
* @return int
* Stack element key of -5 if is empty.
*/
public int pop() {
if (this.is_empty()) return -5;
int key = this.top.key;
this.top = this.top.next;
return key;
}
/**
* Empty method.
*
* Determines if the stack is empty, i.e., if it does not have elements inside.
*
* @return boolean
*/
public boolean is_empty() {
return this.top == null;
}
/**
* Size method.
*
* Determines the size of the stack, i.e., the number of elements of the stack.
*
* @return int
* Number of elements in stack.
*/
public int size() {
if (this.is_empty()) return 0;
StackNode p = this.top;
int i = 0;
while(p != null) {
i++;
p = p.next;
}
return i;
}
/**
* Top method.
*
* Gets the element key in the top of stack, without remove it.
*
* @return int
* Stack element key on the top or -5 if is empty.
*/
public int top() {
return (this.is_empty()) ? -5 : this.top.key;
}
/**
* toString method.
*
* Provide some visual funcionality to see the elements inside the stack.
*
* @return String
* Representation of the stack in the moment by a string.
*/
public String toString() {
if (this.is_empty()) return "Empty stack.";
StackNode p = this.top;
String description = "Stack: ";
while(p != null) {
description += p.key + ", ";
p = p.next;
}
return description;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment