【问题标题】:Recursion on linkedlist : how to compare?链表上的递归:如何比较?
【发布时间】:2021-06-13 04:12:45
【问题描述】:

我目前正在研究链表中的递归,我有一个问题,我必须比较链表中的两个数字,并且我必须递归地进行。

如果列表中的所有元素都按升序排列,则返回true。

这是我在列表中所做的:

public boolean ascending() {
        if(this.first == null) return false;
        return this.first.ascending();
    }

这是我在细胞中所做的:

public boolean ascending() {
        if(this.next != null) {
            if(this.employee.getNumbers() < this.next.employee.getNumbers()) return true;
            this.next.ascending();
        } return false;
    }

问题是我的代码对 100

有什么建议吗?提前谢谢!

【问题讨论】:

  • 你的代码有一个错误:如果你在递归调用你的方法之前返回true,那么你永远不会进入递归

标签: java recursion linked-list


【解决方案1】:

你需要改变你的逻辑

你根本不想返回 true,除非 this.next 为 null,因为这意味着你的数字用完了。

你想要做的是:只要我有数字并且下一个大于当前的数字,就继续寻找。否则返回假。如果我用完了数字,则返回 true。

【讨论】:

  • 太棒了,我懒得写代码了。感谢您从我离开的地方继续
【解决方案2】:

就像David Brossard 解释说你需要类似的东西:

public boolean ascending() 
{
        if(this.next == null)
           return true;
        else if(this.employee.getNumbers() < this.next.employee.getNumbers()) {
           return this.next.ascending();
        } 
        else return false;
 }

【讨论】:

  • 感谢您的建议!我试过这样做,但结果总是错误的。我也不明白为什么如果 next 为 null 则返回 true。我不应该是假的吗?
  • @Evelyne 立即尝试。如果您到达末尾,则意味着在此之前所有数字都按您想要的方式排序,否则您将在之前返回 false
  • 终于成功了!非常感谢,我为这个问题苦苦挣扎了一段时间
  • @Evelyne 我其实有更好的方法
猜你喜欢
  • 2020-01-25
  • 1970-01-01
  • 2014-12-08
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-25
  • 1970-01-01
相关资源
最近更新 更多