简体   繁体   English

双链列表中的hasPrevious()方法

[英]hasPrevious() method in doubly linked lists

For class I am creating a doubly linked list with an iterator. 对于类,我正在使用迭代器创建双向链接列表。 We have just started this sort of stuff, so my experience with it is only a few weeks old. 我们才刚刚开始这种工作,所以我的经验只有几周的历史。

When creating a method to check if a doubly linked list in Java has an element in the previous position behind a cursor, is it proper to use the following code? 当创建一种方法来检查Java中的双链表是否在游标后面的前一个位置中有一个元素时,使用以下代码是否合适?

 public boolean hasPrevious() {
    if(cursor.prev != null){return true; }
    return false;

I am wondering because my professor told me to rethink that method, but I can't really think of where else to go with it. 我很纳闷,因为我的教授告诉我要重新考虑这种方法,但是我真的想不起来还有什么其他方法。 Is there anything certain he may be looking for pertaining to iterators or doubly linked lists that I'm missing? 他可能正在寻找与我所缺少的迭代器或双链表有关的任何东西吗?

edit: Yes, my cursor is part of the iteration. 编辑:是的,我的光标是迭代的一部分。 It is supposed to be between two elements in the code. 它应该在代码中的两个元素之间。

Maybe he wanted you to simplify it a little bit 也许他想让您简化一下

public boolean hasPrevious() {
   if (cursor != null)
      return curser.prev != null;
   return false;
}

The method could be simplified: 该方法可以简化:

public boolean hasPrevious() {
   return cursor != null && cursor.prev != null;
}

I believe this is the most simplified way 我相信这是最简单的方法

public boolean hasPrevious() {
    return (current.previous != null);
}

public E previous() {
    if (hasPrevious()) {
        E result = current.element;
        current = current.previous;
        return result;
    }
    throw new NoSuchElementException();
}

如果您在这里提到的是正确的,那么答案是肯定的。

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

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