Skip to content

Instantly share code, notes, and snippets.

Embed
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){
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