【问题标题】:lookup method in a sorted linked list排序链表中的查找方法
【发布时间】:2020-05-16 18:45:08
【问题描述】:

再来一次!

现在我的问题是我需要创建一个方法查找来搜索链接列表,以便找到一个人并将那个人返回。

public Person lookup(String name) {
    if(head == null) {
        return null;
    }
    if(head.person.name.compareTo(name) == 0) {
        head = head.next;
        return person;
    }

    Node current = head;
    Node prev = head;
    while(current != null) {
        if(current.person.name.compareTo(name) == 0) {
            prev.next = current.next;
            return person;
        }
        prev = current;
        current = current.next;
    }
    return null;
}

现在该方法采用这个参数名称,比较列表中的对象,如果有匹配则应该返回人。我的代码在这里的程序是返回值;正是当比较等于 0 时它返回的值。当我编译时,我得到一个错误,说它找不到符号 person。我如何告诉程序返回找到的人?谢谢!

【问题讨论】:

  • head 声明在哪里?它是什么类型的?该类型是否有 person 字段?
  • Head 是一个 Node 对象,它被声明为 null。

标签: java linked-list return


【解决方案1】:

你可以逐个节点查找查找,像这样:

    public Person lookup(String name) {

        if (head == null) { // check if head is null then Linkedlist is empty and return null
            return null;
        }

        Node current = head; // start from head
        while (current != null) {
            if (current.person.name.equals(name)) { // if equals return person
                return current.person;
            }
            current = current.next; // get the next
        }
        return null;
    }

【讨论】:

  • 你好!我试过实现这个方法,我得到了同样的结果,它找不到符号 person。
  • 是的,应该return current.person; 而不是return person; :)
  • 哦,好吧,我猜我错过了。再次感谢你!你真的是一个救星。干杯伙伴!
  • 你能批准这个解决方案吗:D
  • 哦,是的,确实忘记了。
【解决方案2】:

您应该返回head.personcurrent.person。您的代码不知道person 是什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-30
    • 1970-01-01
    • 2016-06-25
    • 2010-10-28
    • 1970-01-01
    • 1970-01-01
    • 2019-06-30
    • 1970-01-01
    相关资源
    最近更新 更多