Using only stack operations push() and pop() reverse the contents of a stack in the Java programming language
CODE
import java.util.Stack;
public class Main {
public static void main(String[] args)
{
Stack<String> stack = new Stack<String>();
stack.push("a");
stack.push("b");
stack.push("c");
stack.push("d");
stack.push("e");
stack.push("f");
ReverseStack(stack);
System.out.println(stack);
}
public static <T> void ReverseStack(Stack<T> stack)
{
for (int i = 0; i < stack.size(); i++)
{
T targetElement = stack.pop();
ReverseStackStep(stack, stack.size() - i, 0, targetElement);
}
}
public static <T> void ReverseStackStep(Stack<T> stack, int limit, int currentLevel, T targetElement)
{
if (currentLevel == limit)
{
stack.push(targetElement);
}
else
{
T element = stack.pop();
ReverseStackStep(stack, limit, currentLevel + 1, targetElement);
stack.push(element);
}
}
}
Get Answers For Free
Most questions answered within 1 hours.