Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In Java write a method called reverse that accepts a stack of integers and an in

ID: 3718161 • Letter: I

Question

In Java write a method called reverse that accepts a stack of integers and an integer n as parameters and that reverse n values from the bottom of the stack to the top of the stack. For example, if the stack named s stores [1, 2, 3, 4, 5, 6, 7, 8], and we make the call reverse(s, 3); your method should reverse the three values at the bottom of the stack to the top of the stack and leave the other values in the same order, producing [4, 5, 6, 7, 8, 3, 2, 1]. You may assume that the parameter n is not larger than the number of elements in the stack.

In your client code, test your method reverse with the following stacks

[1,3,5,7,9]

[12,13,14,15,16]

Explanation / Answer


import java.util.Stack;

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author Surya
*/
public class reverse {
  
static Stack Reverse(Stack s,int n)//method to reverse n elements from bottom the stack to top
{
Stack<Integer> s1= new Stack<Integer>(),s2= new Stack<Integer>();
  
int m=s.size();//finding size of the stack
  
m=m-n;
  
while(m>0)
{
s1.push(Integer.parseInt(s.peek().toString()));
s.pop();
m--;
}
m = n;
while(m>0)
{
s2.push(Integer.parseInt(s.peek().toString()));
s.pop();
m--;
}
m=s1.size();
while(m>0)
{
s.push(Integer.parseInt(s1.peek().toString()));
s1.pop();
m--;
}

m=s2.size();
while(m>0)
{
s1.push(Integer.parseInt(s2.peek().toString()));
s2.pop();
m--;
}
  
m=s1.size();
while(m>0)
{
s.push(Integer.parseInt(s1.peek().toString()));
s1.pop();
m--;
}
  
return s;
  
}
  
  
public static void main(String argv[])
{
  
Stack<Integer> s = new Stack<Integer>();//creating stack object
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
s.push(6);
s.push(7);
s.push(8);
  
System.out.println("Before reversing :"+s.toString());
s=Reverse(s,3);
System.out.println("After reversing :"+s.toString());
  
  
  
  
}
  
}

output:

run:
Before reversing :[1, 2, 3, 4, 5, 6, 7, 8]
After reversing :[4, 5, 6, 7, 8, 3, 2, 1]
BUILD SUCCESSFUL (total time: 0 seconds)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote