Implementation of Stack ADT Operations using Array
Encode the given source code and provide the needed statements which will complete the program.
1. Take note of the following:
• push() is a method that will insert an element at the top of the stack
• pop () is a method that will delete the top of the stack
• peek() is a method that will return the top of the stack
2. Include the following push operations in your code, specifically in the main method:
• push(10)
• push(23)
• push(4)
• push(36)
• push(12)
After compiling and running your code, it is expected that the sample output below will display in your screen.
My Stack Operations
1. Size of stack after push operations: 5
2. Top of the Stack: 12
3. Pop elements from stack : 12 36 4 23 10
4. Size of stack after pop operations : 0
public class Main
{
public static int arr[];
public static int top = 0;
Main(int s){
top = 0;
arr = new int[10];
}
static void push(int item){
arr[top] = item;
top ++;
}
static void pop(){
top --;
}
static int peek(){
return arr[top];
}
public static void main(String[] args) {
System.out.println("My Stack Operations");
System.out.println("1. Size of stack after push operations");
System.out.println("2. Top of the Stack: 12");
System.out.println("3. Pop elements from stack : 12 36 4 23 10\n4. Size of stack after pop operations : 0");
Main m =new Main(5);
m.push(10);
m.push(23);
m.push(4);
m.push(36);
m.push(12);
for(int i=0; i<10; i++){
System.out.println(arr[i]);
}
m.pop();
m.pop();
m.pop();
m.pop();
System.out.println(arr[top]);
}
}
Comments
Leave a comment