Skip to content

Instantly share code, notes, and snippets.

@dbc2201
Created January 16, 2019 04:48
Show Gist options
  • Save dbc2201/165dd5eed351df755107fd5b8864e5fd to your computer and use it in GitHub Desktop.
Save dbc2201/165dd5eed351df755107fd5b8864e5fd to your computer and use it in GitHub Desktop.
Code for Stack ADT in class Section 2G
package stack;
import java.util.Arrays;
public class Stack
{
int topOfStack = -1;
int[] stack = new int[10];
int size = stack.length;
public static void main(String[] args)
{
Stack stack1 = new Stack();
System.out.println(Arrays.toString(stack1.stack));
/*for (int i = 0; i < 10 ; i++)
{*/
stack1.push(42);
System.out.println(Arrays.toString(stack1.stack));
System.out.println("Top of stack is " + stack1.topOfStack);
int res = stack1.pop();
System.out.println(res + " popped!");
System.out.println(Arrays.toString(stack1.stack));
// }
// TODO add a method for push
}
void push(int value)
{
if (isFull())
{
System.out.println("Overflow!");
}
else
{
topOfStack++;
stack[topOfStack] = value;
}
}
int pop()
{
int response = 0;
if (isEmpty())
{
System.out.println("UnderFlow!");
}
else
{
response = stack[topOfStack];
stack[topOfStack] = 0;
topOfStack--;
}
return response;
}
boolean isEmpty()
{
if (topOfStack == -1)
{
return true;
}
else
{
return false;
}
}
boolean isFull()
{
if (topOfStack == size - 1)
{
return true;
}
else
{
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment