【问题标题】:Java,function does not recognize the return statementsJava,函数无法识别返回语句
【发布时间】:2020-05-20 06:34:50
【问题描述】:

在编写用于检查链表是否为 pallindrome 的代码时,我创建了一个 reverseLL 函数,该函数返回一个反向链表和一个 isPallindrome 函数来检查。问题是循环内的 return 语句没有被检测到并且只有最后一个返回 true 的语句;每次都在执行: 我通过将 LL 分成两部分并反转下半部分来检查 LL 是否是苍白的,然后比较两半

public static Node<Integer> reverseLL(Node<Integer> head){
    Node<Integer> prev = null;
    Node<Integer> current = head;
    Node<Integer> next = null;
    while(current != null) {
        next = current.next;
        current.next = prev;
        prev = current;
        current = next;
    }
    head = prev;
    return head;
}
public static boolean isPallindrome(Node<Integer> head) {
    if(head == null || head.next == null) {
        return true;
    }

    Node<Integer> fast = head;
    Node<Integer> slow = head;

    while(fast.next != null && fast.next.next != null) {
        fast  = fast.next.next;
        slow = slow.next;
    }

    Node<Integer> secondHead = slow.next;
    slow.next = null;
    secondHead = reverseLL(secondHead);

    Node<Integer> p = secondHead;
    Node<Integer> q = head;
    while(p != null) {
        if(p.data != q.data) {
            return false;
        }
        p = p.next;
        q = q.next;
    }
    return true;
}

【问题讨论】:

  • 你试过调试你的代码吗?使用调试器的能力非常重要。
  • 顺便说一句。在我看来,该功能过于复杂。任何适当的 List 实现都应该有 getlength 方法,我只是使用它们来访问我想要比较的元素。
  • 如果你在比较的时候打印值,你会出错
  • @RahulAgrawal 而不是打印值,他应该设置一个断点并逐步观察调试器中的值。正如 Amongalen 所说:使用调试器是一项基本技能。

标签: java loops if-statement linked-list return


【解决方案1】:

我不会运行您的代码,因为它不完整。但是,看起来您找到了列表的最后一个元素并从那里反转它,而没有考虑到它也会反转您已经用head 引用的列表。因此,当您开始比较循环时,您有一个指向反向列表中第一个元素的指针和一个指向反向列表中最后一个元素的指针。您绝对不会将列表分成两部分。

您的代码也过于复杂。正确的算法是:

find head and tail of list
while (head != tail) {
    if (head.value != tail.value)
        return false;
    head = head.next;
    tail = tail.prev;
}

您不需要两个循环变量来查找链表的尾部。正确的算法是:

tail = head
while (tail.next != null) {
    tail = tail.next;
}

此外,您通常不能将整数与相等运算符进行比较。您必须将它们拆箱为原始整数或使用等于。尝试运行:

System.err.println(new Integer(1) == new Integer(1));
System.err.println(new Integer(1).equals(new Integer(1)));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-19
    • 2017-09-05
    • 2020-09-06
    • 2020-02-15
    • 1970-01-01
    相关资源
    最近更新 更多