Last active
August 29, 2018 16:14
-
-
Save xnorcode/4d6372db2b58922b7127fa1e49e13453 to your computer and use it in GitHub Desktop.
Reversing a String using Stack in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
... | |
// create a stack of characters | |
Stack<Character> st = new Stack<Character>(); | |
// convert string to reverse into an array of characters | |
char[] arr = str.toCharArray(); | |
// iterate chars array and push each char into the stack | |
for(char c : arr){ | |
st.push(c); | |
} | |
// pop all chars from the stack into the new array | |
for(int i = 0; i < arr.length; i++){ | |
arr[i] = st.pop(); | |
} | |
// print reversed string | |
System.out.println(new String(arr)); | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment