In Java public class Stack { int maxsize=10; int[] stackarray=new int[maxsize];
ID: 3930961 • Letter: I
Question
In Java
public class Stack {
int maxsize=10;
int[] stackarray=new int[maxsize];
int top=-1;
void push(int a)
{
if(top+1>=maxsize)
//Your Code goes here
}
void pop()
{
if(top<0)
//Your code goes here
}
void top()
{
//Your code goes here
}
void print()
{
//Your code goes here
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Stack s=new Stack();
s.push(3);
s.push(34);
s.push(33);
s.push(93);
s.push(34);
s.push(33);
s.push(93);
s.push(34);
s.push(33);
s.push(93);
s.push(93);
s.top();
s.pop();
s.top();
s.push(67);
s.print();
}
}
Explanation / Answer
public class Stack {
int maxsize=10;
int[] stackarray=new int[maxsize];
int top=-1;
void push(int a)
{
if(top+1>=maxsize) //checking whether top is not greater than maxsize
System.out.println("stack is full");
else
{stackarray[top+1]=a; //push at the top location of the array
top++;} //increase the index of top
//Your Code goes here
}
void pop()
{
if(top<0) //checking whether top is not less than 0
System.out.println("Stack is empty..!!..nothing to delete");
else
{stackarray[top]=0; //pop the element,here i am filling value zero,i.e main element is popped from array and zero is filled
top--; //decrease the index value of top
}
//Your code goes here
}
void top()
{
for(int i=0;i<maxsize;i++)
{if(stackarray[i]==0) //if value in array is zero,then index-1 will be the index of top as we are assuming zero value means no element in stackarray
{
top=i-1;
break;
}
}
}
void print()
{int i=top;
System.out.println("value in stack");
while(stackarray[i]!=0) //printing the stack i.e array in reverse order
{
System.out.println(stackarray[i]);
i--;
}
//Your code goes here
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Stack s=new Stack();
s.push(3);
s.push(34);
s.push(33);
s.push(93);
s.push(34);
s.push(33);
s.push(93);
s.push(34);
s.push(33);
s.push(93);
s.push(93);
s.top();
s.pop();
s.top();
s.push(67);
s.print();
}
}
***********OUTPUT************
stack is full
value in stack
67
33
34
93
33
34
93
33
34
3
***********OUTPUT************
Please let me know in case of any question.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.