繁体   English   中英

Java链表查找方法

[英]java linkedlist find method

我在执行Java实验室作业时遇到困难。

这是我的代码和说明:

如果密钥不存在,则应返回PREVIOUS节点。 如果没有上一个(key == Aaron),则返回null。

 protected Node<K, V> find (K key, Node start) {
  for (Node<K, V> node = start == null ? head : (Node<K, V>) start;
  node != null; node = node.next){
    if(key.equals(node.key)){
        return node;
    }
    else if(!key.equals(node.key)){
        node=node.next;
    }
    else{
        return null;
    }
  }
  return tail;
}

CEGIKMOQSUWY

2 4 6 8 10 12 14 16 18 20 22 24

这是链表。

我的输出是CEGIKMOQSUWY 2 4 6 8 10 12 14 16 18 20 22 24

containsKey(A)= false

containsKey(C)= true

containsKey(L)= false

containsKey(M)= false

containsKey(Y)= true

containsKey(Z)= false

但是对于M,它也应该返回true我该如何解决此问题?

您可以通过使用双链表或(这意味着您必须在node类中进行更改)来解决此问题,另一种方法是在指向头部时,另一个必须指向头部,而另一个则在头部之后,

node p = null ; 
node q = head ;

每次循环时,您都会

 p = q and q = q.next();

因此,这样,如果找不到键,则返回p;找到键,则返回q。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM