The code works well. It's just i don't get it. Having difficult in the recursive part. In this part: char a = st.peek();st.pop(); insert_at_bottom(x); st.push(a); my idea is that first it will execute char a = st.peek();st.pop() all the time until a threshold. then it will execute st.push(a); one time. So the a will only be assigned value once. Obviously that is not true.
The difficult part for me is in the insert_at_bottom method what does insert_at_bottom(x) do? in reverse method what does reverse(), insert_at_bottom(x)do?
import java.util.Stack;
class Test {
static Stack<Character> st = new Stack<>();
static void insert_at_bottom(char x)
{
if(st.isEmpty()) st.push(x);
else
{char a = st.peek();
st.pop();
insert_at_bottom(x);
st.push(a);
}
}
static void reverse()
{
if(st.size() > 0)
{
char x = st.peek();
st.pop();
reverse();
insert_at_bottom(x);
}
}
public static void main(String[] args)
{ st.push('1'); st.push('2'); st.push('3'); st.push('4');
System.out.println("Original Stack");
System.out.println(st);
reverse();
System.out.println("Reversed Stack");
System.out.println(st); }}
st.size() > 0, you should probably use!st.isEmpty(). Depending on the implementation ofStack, finding the size of the stack can be much slower than checking whether it's empty. And there's no way that checking the size can be appreciably slower than checking emptiness.