【问题标题】:Reverse words from SCANNER using STACK and RECURSION使用 STACK 和 RECURSION 从 SCANNER 反转单词
【发布时间】:2014-02-04 08:29:37
【问题描述】:

有没有办法从 SCANNER 获取单词并使用 STACK 和 RECURSION 反转它们?我需要这个程序中的所有三个方面。我可以单独使用 Stack 或单独使用 Recursion 来做到这一点,但我无法让两者一起工作。

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(); 
    }
}

【问题讨论】:

  • 好的,我们马上开始你的作业......
  • 递归一个堆栈/取消堆栈操作,虽然是隐式的。
  • Kevin 如果你上过学,你应该知道此时没有学校。这是我选择自己做的练习。请发布有用的东西或根本不发布。谢谢

标签: java recursion stack


【解决方案1】:

递归时首先要记住的是定义停止条件;

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-11
    • 1970-01-01
    • 2018-07-17
    • 1970-01-01
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多