How can i change this code to reverse a stack recursively (using an ArrayStack o
ID: 3918579 • Letter: H
Question
How can i change this code to reverse a stack recursively (using an ArrayStack or a LinkedStack)?
import java.util.Scanner;
public class ReverseTokens {
public static void main(String args[]) {
//This allows us to get user input
Scanner input = new Scanner(System.in);
System.out.print("Enter some words: ");
String userText = input.nextLine();
//Whatever the user entered in now in userText
//Put tokens (space separated) into an array
String[] userTokens = userText.split(" ");
//...
ArrayStack<String> reverse = new ArrayStack<String>();
for (int i=0; i<userTokens.length; i++)
reverse.push(userTokens[i]);
while(!reverse.isEmpty())
System.out.print(reverse.pop() + " ");
}
Explanation / Answer
I think you want to reverse the Strings, not stack [assuming that’s a mistake in question] using recursion with the help of ArrayStack. Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts. Thanks
// ReverseTokens.java
import java.util.Scanner;
public class ReverseTokens {
public static void main(String args[]) {
// This allows us to get user input
Scanner input = new Scanner(System.in);
System.out.print("Enter some words: ");
String userText = input.nextLine();
// Whatever the user entered in now in userText
// Put tokens (space separated) into an array
String[] userTokens = userText.split(" ");
// ...
ArrayStack<String> stack = new ArrayStack<String>();
//reversing the String
reverseString(userTokens, 0, stack);
System.out.println();
}
/**
* method to reverse a String and print it, using an ArrayStack
*
* @param words
* - words list
* @param index
* - starting index
* @param stack
* - empty ArrayStack
*/
static void reverseString(String[] words, int index,
ArrayStack<String> stack) {
if (index < words.length) {
//pushing current character to the array stack
stack.push(words[index]);
//invoking the method recursively
reverseString(words, index + 1, stack);
//popping and printing the top character
System.out.print(stack.pop() + " ");
}
}
}
/*OUTPUT*/
Enter some words: Conversations with little ones are so precious and joyful
joyful and precious so are ones little with Conversations
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.