簡體   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