繁体   English   中英

没有指针的循环链表

[英]A Circular linked list with no pointers

我正在尝试完成循环双向链接列表编程项目。 我们假设使用Node<E> Head作为唯一的即时变量来创建链接列表类。 内部类中唯一的即时变量是Node current。 Node类具有三个即时变量,即E dataNode<E> nextNode<E> prev

在使用CDLL调用的测试程序中,我们假设使用迭代器内部类的next()hasNext()方法在打印出每个节点后遍历整个列表。 我遇到的问题是我无法弄清楚hasNext()方法如何知道何时完成一个循环并已打印每个节点。

换句话说,如何让hasNext()在循环的第一次迭代中在current==head时返回true,而在第二次循环的开始时在current==head时返回false。

我非常感谢您可能有任何见解。

由于实例变量的限制,这似乎是不可能的。

但是,如果不将尾节点链接到头节点,则可以实现“ hasNext”。

然后它将不再是圆形的。

但是您不必使列表实际上是循环的。

如果发现下一个节点为空,则改为获取头节点。

那么它将几乎是圆形的。

编辑:

换句话说,如何让hasNext()在循环的第一次迭代中在current == head时返回true,而在第二次循环的开始时在current == head时返回false。

所以您的问题是,重要的是current == head。 没关系,在循环情况下,nextNode()才是重要的,也就是说,接下来会发生什么?

因此,假设HEAD是对列表开头的引用,并且最后一个节点.next()指向HEAD节点。

// psudocode.
boolean hasNext() 
   if current.next() == head 
       return false
   else
      return true

编辑:

好的,这是执行此迭代的非常简单的版本

public void iterateAndPrint(Node head) :
   Node current = head;
   // check for null case
   if(current == null)
       return
   // case of list where ther eis only one node - HEAD...
   if(!current.hasNext())  
       print current.name
       return
   // ok so the nodes aren't empty, and there are more than just the head node.
   while(true): 
      // as long as has next returns true, print the name and then set current to next node
      if(current.hasNext())
          print current.name
          current = current.next()
      // has next returned false - we're on the last node.  Make sure it's not equal to Head (redundant at this point)
      else if (!current.hasNext() && current!=head) 
          print current.name
          break
      // i don't think this is strictly nescesary, but better safe than sorry.
      else:
          break      
public void hasNext(Node current, Node head):
      if(current.next() == head):
          return false
      else:
          return true

暂无
暂无

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

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