In: Computer Science
Write method reverseStack(Stack s) that receives a stack s and reverse the order of its elements.
the values inside the stack must be changed, that the top will be the last and so on.
please use java code to slove.
Thank you.
Program in java:
import java.util.Stack;
import java.util.Scanner;
public class Main
{
public void insert_at_bottom_of_stack(Stack<Integer> stack,
int x){
if(stack.isEmpty()){//check if stack is empty
stack.push(x);
return;
}
//take out the existing items in stack and keep it in method
stack
int n = stack.pop();
//push x to the bottom of stack
insert_at_bottom_of_stack(stack, x);
//push back all the items from method stack to stack
stack.push(n);
}
public void reverse(Stack<Integer> stack){
if(stack.isEmpty()==false){// if function is not empty
//pop out all the items from the stack and store it in method
stack
int n1 = stack.pop();
reverse(stack); //insert the items into stack in reversed
order
// by recursivly call reverse method
insert_at_bottom_of_stack(stack, n1);//pop last item from the
stack
}
}
public static void main(String[] args) {
Stack<Integer> InputStack = new Stack<>();
Scanner sc=new Scanner(System.in);
System.out.println("Enter number of element you want to enter in a
stack");
int number=sc.nextInt();
int element;
for(int i=0;i<number;i++){
System.out.println("Enter "+(i+1)+ " elemnt in stack");
element=sc.nextInt();
InputStack.add(element);
}
System.out.println("Input Stack is : " + InputStack);
Main obj = new Main();
obj.reverse(InputStack);
System.out.println("Reversed Stack is: " + InputStack);
}
}
Outout 1:
Output 2:
Program Screenshot:
Method for reverse stack:
public void insert_at_bottom_of_stack(Stack<Integer>
stack, int x){
if(stack.isEmpty()){//check if stack is empty
stack.push(x);
return;
}
//take out the existing items in stack and keep it in method
stack
int n = stack.pop();
//push x to the bottom of stack
insert_at_bottom_of_stack(stack, x);
//push back all the items from method stack to stack
stack.push(n);
}
public void reverse(Stack<Integer> stack){
if(stack.isEmpty()==false){// if function is not empty
//pop out all the items from the stack and store it in method
stack
int n1 = stack.pop();
reverse(stack); //insert the items into stack in reversed
order
// by recursivly call reverse method
insert_at_bottom_of_stack(stack, n1);//pop last item from the
stack
}
}