Java 使用堆栈和递归从扫描仪反转单词
有没有一种方法可以从扫描器中获取单词,并使用堆栈和递归将其反转?我需要这个计划的所有三个方面。我可以单独使用堆栈或递归来实现这一点,但我无法使两者一起工作Java 使用堆栈和递归从扫描仪反转单词,java,recursion,stack,Java,Recursion,Stack,有没有一种方法可以从扫描器中获取单词,并使用堆栈和递归将其反转?我需要这个计划的所有三个方面。我可以单独使用堆栈或递归来实现这一点,但我无法使两者一起工作 public class Reverse { public static String wordReverse(String[] theWords) { Stack <String> stacker = new Stack <String>(); for(String words
public class Reverse {
public static String wordReverse(String[] theWords) {
Stack <String> stacker = new Stack <String>();
for(String wordsHold : theWords) {
stacker.push(wordsHold);
}
while ( !stacker.empty() ) {
stacker.pop();
}
return wordReverse(theWords); // Cause of StackOverflowError
}
public static void main(String args[]) {
Scanner takeIn = new Scanner(System.in);
String allWords = takeIn.nextLine();
String[] goodWords = allWords.split(" ");
System.out.println(wordReverse(goodWords));
takeIn.close();
}
}
递归时要记住的第一件事是定义停止条件
public static String wordReverse(String[] theWords, Stack<String> stack) {
// stop on null.
if (theWords == null) {
return null;
} else if (theWords.length < 2) {
// stop if there are fewer then two words.
return theWords[0];
}
// push the first word.
stack.push(theWords[0]);
// copy the sub-array.
String[] s = new String[theWords.length - 1];
System.arraycopy(theWords, 1, s, 0, theWords.length - 1);
// recurse
return wordReverse(s, stack) + " " + stack.pop();
}
public static String wordReverse(String[] theWords) {
// call the recursive implementation with a new Stack.
return wordReverse(theWords, new Stack<String>());
}
public static void main(String args[]) {
Scanner takeIn = new Scanner(System.in);
String allWords = takeIn.nextLine();
String[] goodWords = allWords.split(" ");
System.out.println(wordReverse(goodWords));
takeIn.close();
}
当然,我们会马上开始你的家庭作业……递归是一个堆栈/取消堆栈操作,虽然是隐式的。凯文如果你去上学,你应该知道现在没有学校。这是我自己选择的做法。请发布一些有用的东西,或者根本不发布。谢谢
Hello world, goodbye world
world goodbye world, Hello