Skip to content

Instantly share code, notes, and snippets.

Last active August 29, 2018 16:14
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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){
// 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