JavaAlgorithms/DataStructures/Stacks/StackArrayList.java

98 lines
2.4 KiB
Java
Raw Normal View History

2020-01-29 00:18:15 +08:00
package DataStructures.Stacks;
import java.util.ArrayList;
/**
* This class implements a Stack using an ArrayList.
2019-01-06 09:01:33 +08:00
* <p>
* A stack is exactly what it sounds like. An element gets added to the top of
* the stack and only the element on the top may be removed.
2019-01-06 09:01:33 +08:00
* <p>
* This is an ArrayList Implementation of a stack, where size is not
* a problem we can extend the stack as much as we want.
*
* @author Unknown
*/
2019-01-06 09:01:33 +08:00
public class StackArrayList {
2019-01-06 09:01:33 +08:00
/**
* Main method
*
* @param args Command line arguments
*/
public static void main(String[] args) {
StackArrayList myStackArrayList = new StackArrayList();
myStackArrayList.push(5);
myStackArrayList.push(8);
myStackArrayList.push(2);
myStackArrayList.push(9);
2019-01-06 09:01:33 +08:00
System.out.println("*********************Stack List Implementation*********************");
System.out.println(myStackArrayList.isEmpty()); // will print false
System.out.println(myStackArrayList.peek()); // will print 9
System.out.println(myStackArrayList.pop()); // will print 9
System.out.println(myStackArrayList.peek()); // will print 2
System.out.println(myStackArrayList.pop()); // will print 2
}
2019-01-06 09:01:33 +08:00
/**
* ArrayList representation of the stack
*/
private ArrayList<Integer> stackList;
2019-01-06 09:01:33 +08:00
/**
* Constructor
*/
public StackArrayList() {
stackList = new ArrayList<>();
}
2019-01-06 09:01:33 +08:00
/**
* Adds value to the end of list which
* is the top for stack
*
* @param value value to be added
*/
public void push(int value) {
stackList.add(value);
}
2019-01-06 09:01:33 +08:00
/**
* Pops last element of list which is indeed
* the top for Stack
*
* @return Element popped
*/
public int pop() {
2019-01-06 09:01:33 +08:00
if (!isEmpty()) { // checks for an empty Stack
int popValue = stackList.get(stackList.size() - 1);
stackList.remove(stackList.size() - 1); // removes the poped element from the list
return popValue;
}
2019-01-06 09:01:33 +08:00
System.out.print("The stack is already empty!");
return -1;
}
2019-01-06 09:01:33 +08:00
/**
* Checks for empty Stack
*
* @return true if stack is empty
*/
public boolean isEmpty() {
return stackList.isEmpty();
}
2019-01-06 09:01:33 +08:00
/**
* Top element of stack
*
* @return top element of stack
*/
public int peek() {
return stackList.get(stackList.size() - 1);
}
}