Reversing a String

We need to make use of a stack data structure for reversing a string.

Follow these steps:

  1. 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) 
  1. 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

Go to 
https://goo.gl/UN2d5U to access the code. 

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.232.11