Skip to content

Instantly share code, notes, and snippets.

@pedrofurtado
Created January 3, 2016 16:20
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/ddee355aab1f39f36777 to your computer and use it in GitHub Desktop.
Save pedrofurtado/ddee355aab1f39f36777 to your computer and use it in GitHub Desktop.
Implementation of Stack (in vector) in Java
/**
* @file
* Stack.
*
* Implementation with vector.
* It's used nested class to improve encapsulation.
*
* @author Pedro Furtado
*/
public class StackVector {
/**
* Properties of stack.
*/
private int max = 5;
private int top = -1;
private StackNode[] A = new StackNode[this.max];
/**
* Element of stack.
*/
class StackNode {
public int key;
public StackNode next = null;
}
/**
* Default constructor method.
*/
StackVector() {
for (int i = 0; i < this.max; i++) {
this.A[i] = new StackNode();
}
}
/**
* 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 == -1;
}
/**
* Full method.
*
* Determines if the stack is full, i.e., if all vector indexes are filled with stack elements.
*
* @return boolean
*/
public boolean is_full() {
return this.top == this.max - 1;
}
/**
* Push method.
*
* Add an element to the top position of the vector stack.
*
* @param int key
* Integer key.
* @return void
*/
public void push(int key) {
if (this.is_full()) return;
this.top++;
this.A[this.top].key = key;
}
/**
* Pop method.
*
* Remove the element on the top position of vector stack.
*
* @return int
* Stack element key of -5 if is empty.
*/
public int pop() {
if (this.is_empty()) return -5;
int key = this.A[this.top].key;
this.top--;
return key;
}
/**
* 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() {
return this.top + 1;
}
/**
* 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 vector.";
String description = "Stack Vector: [ ";
for (int i = 0; i <= this.top; i++) {
description += this.A[i].key + ", ";
}
description += " ]";
return description;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment