Click here to Skip to main content
15,893,161 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
import java.util.*;
public class Reverse_A_Stack_Using_Recursion

{
    static void insert_at_bottom(Stack st, int x)
    {
     int y;
     if(st.size() == 0)
     {
         st.push(x);
     }else
     {
       y = st.peek();
       st.pop();
       insert_at_bottom(st,x);
       st.push(y);
     }   
    }
    static void reverse(Stack st)
    {
     int x;
     if(st.size() > 0)
     {
         x = st.peek();
         st.pop();
         reverse(st);
         insert_at_bottom(st,x);
     }   
    }
   public static void main(String []args)
   {
        Stack<Integer> st = new Stack<Integer>();
        st.push(4);
        st.push(3);
        st.push(2);
        st.push(1);
        reverse(st);
       System.out.println(st);  
        
    }
    
}


What I have tried:

Stack i have is of Integer then why while peeking an object is peeked
Posted
Updated 5-Jan-22 20:51pm

Because when you declare the method, you say this:
static void insert_at_bottom(Stack st, int x)
Which means that st can contain any value: an Object, and you can;t automatically convert an Object to any other type.

Instead, tell the system what your stack contains, and it'll understand what you are doing:
static void insert_at_bottom(Stack<Integer> st, int x)
You will need to do the same to your reverse method as well.
 
Share this answer
 
A shorter way of resolving the issue is to force type casting from object to int.

x = Convert.ToInt32(st.peek());


You need to convert object to int on all peek() calls.

But more elegant approach would be to use the way that @OG has suggested.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900