Skip to content

Instantly share code, notes, and snippets.

@xnorcode
Last active August 29, 2018 16:14
Show Gist options
  • Save xnorcode/4d6372db2b58922b7127fa1e49e13453 to your computer and use it in GitHub Desktop.
Save xnorcode/4d6372db2b58922b7127fa1e49e13453 to your computer and use it in GitHub Desktop.
Reversing a String using Stack in Java
...
// 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