Stack Assignment
Stack Assignment
Department of Computer Science, University of the People
CS 3303-01: Data Structures AY2022-T5
Professor Shuchi Dhir
July 6, 2022
Stack Assignment
2
Stack Assignment
For this example I would be using the algorithm that performs basic stack operations,
for example "pushO", and "popO" and using an array of static size. I would be following the
next few steps to get it work as expected
1. Creating a stack class which will hold an object in the main class.
2. I will be using the Push three elements as instructed to the stack object one by one by using
the pushO method.
3. Then, I will be popping all three elements from the stack object by using the popO method
4. Creating an array of static size inside the Stack class.
5. Using the constructor, initializing the top of the stack to be -1.
6. Creating a method inside the pushO which would be showing if the top>= Max size -1 then
it will be posting a message like "Stack is Full."
7. if the top <0 then it will show another message for example "Stack is Empty" inside the
pop0.
import java.util.*;
class for stack operation class Stack { static final int MAX = 1000; int top; int stck[] = new int[MAX];
// define max size of stack
// constructor Stack() J top = -1;
// initialize top of the stack
// insert element to the stack boolean push(int x)
if (top >= (MAX - 1 { System.out.println("Stack is full"); return false;
// display message
else {
Stack Assignment
3
stck[++top] = x; // add element to the stack System.out.println(x + " pushed into stack"; return true;
this method will return the top of the stack int pop()
if (top < 0) { // if empty then display message System.out.println("Stack is empty"); return 0;
else { int x = stck[top--]; return x;
// Driver class class Main { public static void main(String args[])
Stack st = new Stack(); //create stack object // add element to the stack st.push(10); st.push(20); st.push(30); System.out.println(); // remove element from the stack System.out.println(st.pop() + " Popped from stack");
System.out.println(st.pop() + " Popped from stack");
And the Outputs would be 10 pushed into stack 20 pushed into stack 30 pushed into stack
30 Popped from stack 20 Popped from stack 10 Popped from st