Skip to content

Instantly share code, notes, and snippets.

@dbc2201
Created February 3, 2019 10:11
Show Gist options
  • Save dbc2201/ea845fec7c44f0d2e0e6cddb654051d6 to your computer and use it in GitHub Desktop.
Save dbc2201/ea845fec7c44f0d2e0e6cddb654051d6 to your computer and use it in GitHub Desktop.
CodeRelease #1: Integer Stack ADT in Java
package release;
import java.util.Scanner;
public class StackADT
{
// members for the class;
// integer array for stack; integer variable for top of stack
private int[] stackArray;
private int topOfStack;
public StackADT(int numberOfElements)
{
stackArray = new int[numberOfElements];
topOfStack = -1;
}
// push an integer element at the top of the stack
public void push(int element)
{
if (isFull()) // the stack is already full
{
System.out.println("Stack is already full!");
}
else
{
topOfStack++;
stackArray[topOfStack] = element;
}
}
// remove the element at the top of the stack
public int pop()
{
int response = 0;
if (isEmpty())
{
System.out.println("Stack is already empty!");
}
else
{
response = stackArray[topOfStack];
stackArray[topOfStack] = 0;
topOfStack--;
}
return response;
}
// check whether the stack is full
public boolean isFull()
{
boolean response = false;
if (topOfStack == stackArray.length - 1)
{
response = true;
}
return response;
}
// check whether the stack is empty
public boolean isEmpty()
{
boolean response = false;
if (topOfStack == -1)
{
response = true;
}
return response;
}
// implement a dsiplay method for the stack
public void display()
{
System.out.println("---");
if (isEmpty())
{
System.out.println("Stack is empty!");
}
else
{
for (int i : stackArray)
{
if (i != 0)
{
System.out.println(i);
}
}
}
System.out.println("---");
}
public static void main(String[] args)
{
System.out.println("How many elements would you like in your stack?");
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
StackADT stackObject = new StackADT(n);
stackObject.display();
for (int i = 0; i < n; i++)
{
System.out.print("Enter the " + i + "th element: ");
int element = scanner.nextInt();
stackObject.push(element);
}
stackObject.display();
int removedElement = stackObject.pop();
System.out.println(removedElement + " was removed");
System.out.println("Stack after removing " + removedElement);
stackObject.display();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment