Lab Session # 5 Stacks: Answer To Question # 1 and 2
Lab Session # 5 Stacks: Answer To Question # 1 and 2
Stacks
Answer to Question # 1 and 2:
PUSH:
Code:
package lab5;
import java.util.*;
int STACK[]=new int[MAXSTK]; //creating a new stack of type int and length MAXSTK
int TOP=-1; //setting the TOP (last in element index) of the STACK
String in=input.next();
while(in.equals("Y")){
int element=input.nextInt();
TOP=k;
STACK[k]=element;
k++;
System.out.println("if you want to add another item please write Y else N: ");
in=input.next();}
System.out.println("TOP before PUSH operation: "+TOP);
if(MAXSTK==TOP+1){
System.out.println("Stack Overflow!!");}
else{
//printing STACK
for(int i=0;i<STACK.length;i++){
System.out.println(STACK[i]);}
Output:
Output by the above code:
Output by setting MAXSTK=3 and ITEM=77 and getting TOP=1
POP:
Code:
package lab5;
import java.util.*;
int a=input.nextInt();
String in=input.next();
while(in.equals("Y")){
int element=input.nextInt();
TOP=k;
STACK[k]=element;
k++;
System.out.println("if you want ot add another item please write Y else N: ");
in=input.next();}
if(TOP==-1){
System.out.println("Stack Underflow!!");}
else{
//printing STACK
for(int i=0;i<STACK.length;i++){
System.out.println(STACK[i]);}
Output:
Output by the above code:
Answer to Question # 3:
Code:
package lab5;
import java.util.*;
STACK[0]=1;
STACK[1]=2;
STACK[2]=3;
STACK[3]=4;
String op=input.next();
if(op.equals("POP")){
if(TOP==-1){
System.out.println("Stack Underflow!!");}
else{
//printing STACK
for(int i=0;i<STACK.length;i++){
System.out.println(STACK[i]);}
else if(op.equals("PUSH")){
if(MAXSTK==TOP+1){
System.out.println("Stack Overflow!!");}
else{
//printing STACK
for(int i=0;i<STACK.length;i++){
System.out.println(STACK[i]);}