使用递归反转列表元素

4151820709

目的是编写代码,以借助递归来反转列表的元素。

public static List<Integer> reverse(List<Integer> input) {
    if (input.isEmpty()) {
        return new LinkedList<Integer>();
    } else {
        List<Integer> output = new LinkedList<Integer>();
        output.add(((LinkedList<Integer>) input).removeLast());
        reverse(input);
        return output;
    }
}

不幸的是,我只正确地获得了第一个元素,而列表的其余部分却没有出现。我想念什么?

Prasad Karunagoda

您可以像下面的代码那样执行此操作。请注意,我正在使用removeFirst()方法。

import java.util.LinkedList;
import java.util.List;

public class Reverse {

  public static List<Integer> reverse(List<Integer> input) {
    if (input.isEmpty()) {
      return new LinkedList<Integer>();
    } else {
      Integer first = ((LinkedList<Integer>) input).removeFirst();
      List<Integer> output = reverse(input);
      output.add(first);
      return output;
    }
  }

  public static void main(String[] args) {

    List<Integer> input = new LinkedList<>();
    input.add(15);
    input.add(37);
    input.add(26);
    input.add(18);
    input.add(31);

    System.out.println("Input  : " + input);
    System.out.println("Output : " + reverse(input));
  }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章