【问题标题】:Why temp.data == temp.next.data gives an error?为什么 temp.data == temp.next.data 会出错?
【发布时间】:2021-11-20 06:05:41
【问题描述】:

我正在做一个从 LinkedList 中删除重复项的问题。首先在 if 语句中编写了此代码我已经编写了 if(curr.data == curr.next.data) 但它显示错误,并且在一个测试用例中显示运行时错误。两者不是一样吗?使用(curr.data.equals(curr.next.data))有什么区别?

public static LinkedListNode<Integer> removeDuplicates(LinkedListNode<Integer> head) {
        //Your code goes here
        if (head == null)
            return null;
        LinkedListNode<Integer> curr = head;
        while(curr.next != null)
        {
            if(curr.data == curr.next.data)
            {
                curr.next = curr.next.next;
            }
            else
            {
                curr = curr.next;
            }
        }
        return head;
    }

【问题讨论】:

  • ==equals() 之间的区别:stackoverflow.com/questions/7520432/…。你知道那个测试用例的输入是什么吗?
  • @LinuxGeek 不,测试用例被锁定
  • @anarchist912 那是 Java
  • 我认为你应该考虑@LinuxGeek 的回答。

标签: linked-list singly-linked-list dsa


【解决方案1】:

改变

while(curr.next != null)

while(curr != null)

if 块中,您正在检查curr.next = curr.next.next,但如果curr.next.next 本身就是null,如果它是null,那么while 中的条件将导致错误。

【讨论】:

  • curr.next设置为null会不会报错?我认为它只会结束 while 循环,因为不再满足条件。 PS:是curr 不是cur
  • @anarchist912 当curr 本身为空时,您将如何访问curr.next(就像他/她在while 中所做的那样)。考虑到链表中只有 2 个节点,并且两个节点的值都为 10。现在尝试运行循环,if 条件为真,所以curr 将设置为curr.next.next(即null)所以当它再次达到while 条件curr.next != null 将导致错误,因为curr 已经是null。是的,谢谢我现在将cur 更改为curr
猜你喜欢
  • 2021-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多