We need to make use of a stack data structure for reversing a string.
Follow these steps:
- To reverse the string, push of each character of the input string and then pop everything out, one at a time, building a reversed string. The method signature can be as follows:
public String reverse(String str)
- The following code shows how a string can be reversed using the stack data structure:
public String reverse(String str) {
StringBuilder result = new StringBuilder();
Stack<Character> stack = new Stack<>();
for (char c : str.toCharArray())
stack.push(c);
Optional<Character> optChar = stack.pop();
while (optChar.isPresent()) {
result.append(optChar.get());
optChar = stack.pop();
}
return result.toString();
}
Snippet 2.23: Reverse a string solution Source class name: StringReverse
Stack data structures are extensively used in computer science for many algorithms. In this section, we have seen how to implement them in a dynamic fashion using linked lists. In the next section, we shall see how to model stacks and queue in a static manner using arrays.