2011-03-10 35 views
0

我試圖寫在這個問題上的算法(從一個測驗,沒有家庭作業):算法打印循環鏈表

編寫一個函數的算法來 打印出存儲在 圓形的信息名單。確保您的 算法適用於空列表, 列表僅包含一個節點,而 列表包含許多節點。

我的算法打印信息<val list metadata>。該算法將信息打印在循環列表中。

if (newptr != null) // check is list empty or not 
    firstnod = head // if it's not, save the first nod's data because it's circular list 
    print newptr.data 
end if 
loop (newptr.data != firstnod) 
    print newptr.data 
    count += 1 
end loop 

回答

2

需要更新循環中的newptr。否則,你將永遠得到相同的元素,並且是一個無限循環。

loop newptr != firstnod 
    print newptr.data 
    newptr = newptr.nextnode 
endloop 

編輯1:

if list != NULL 
    print list.data 
    if list.nextNode != NULL 
     Node* head, temp 
     head = list 
     temp = list.nextNode 
     while(temp != head) 
      print temp.data 
      temp = temp.nextNode 
     End while 
    else 
     print "Next node is not intialized"; 
else 
    print "List is empty"; 
+0

亞,但我可適當增加計數或不夠 – hana 2011-03-10 08:26:34

+0

@hana - 增加計數不使指針指向下一個節點的鏈接列表。 – Mahesh 2011-03-10 08:27:35

+0

好的,謝謝你alooot – hana 2011-03-10 08:30:45