2013-04-28 148 views
0

我在找出一個函數的實現時遇到了一點問題。遞歸顯示嵌套列表

基本上,我有一個嵌套列表,我需要像這樣顯示出來:

Root 
    -RItem1 
     --Item1 
     --RRItem2 
     --Item1 
     --Item2 
    -RItem2 
     --RRItem1 
      -Item1 
      -Item2 
     --Item2 

注意,我會在運行系統中獲取數據。一個物品可能有一個物品,有一個物品有物品等。

所以基本上,一個程序如何呢?我知道遞歸函數是要走的路,但我遇到了麻煩。具體來說,我很難考慮我的物品的座標。

這是一個執行問題,所以語言並不重要。

+0

可不可以給這些名單是如何嵌套的一個例子即 '[ 「RItem1」,[ 「項目1,[」 RRItem2" ,[ 「項目1」],[ 「項目2」]]]]' – HennyH 2013-04-28 13:42:27

+0

@ HennyH不幸的是,數據使用鏈接列表以相當複雜的方式排列。 – Secret 2013-04-28 13:48:17

回答

3

遞歸函數是一個好方法。你必須通過'水平'作爲參數。類似的東西(假的Java/Java腳本):

function display(item, level) { 
    printlnAtLevel(level,item.name) 
    if item.hasChildren() { 
     foreach(child : item.children) { 
      display(child,level+1) 
     } 
    } 
} 
display(root,0) 
+0

謝謝@ l4mpi,我編輯了我的帖子。 – Thierry 2013-04-28 12:17:41

+0

我決定不接受這個答案,因爲我覺得y座標是一個問題。經過很多思考,我意識到這是一個問題,我仍然無法做到。我怎麼能決定y?我可以將函數作爲全局函數保存在外部,但我怎樣才能「遞歸地」執行它。哦,非常感謝:3 – Secret 2013-04-28 13:25:25

+0

在上面的代碼中,如果我有1. {a,b} 2.「2」將其級別設爲「1」,而不是b。如果我的解釋很難理解,請回復,我會盡量詳細說明。謝謝! – Secret 2013-04-28 13:34:51

1

我寄與(X,Y)另外一個答案:

function display(item, x, y) { 
    print(x,y,item.name) 
    if item.hasChildren() { 
    yTemp = y + 1 
    foreach(child : item.children) { 
     display(child,x+1,yTemp++) 
    } 
    } 
} 
display(root,0,0) 
1
def nodePrint(val,depth): 
    print(" "*depth + "-"*depth,val) 

def recPrint(l,depth=0): 
    #node has no children A) it contains 1 or 0 elements B) if not A then'child' is string 
    if len(l) <= 1 or isinstance(l[1],str): 
     for value in l: 
     nodePrint(value,depth) 
    else: 
     #node had both head and child in form [ head, [ child1, ... ] ] 
     head, children = l[0],l[1:] 
     nodePrint(head,depth) 
     for child in children: 
     recPrint(child,depth+1) 

使用下列內容:

t = ["Root", 
    [ 
     "Ritem1", 
      [ 
       "Item1", 
       [ 
       ] 
      ], 
      [ 
       "RRItem2", 
       [ 
       "Item1", 
       "Item2" 
       ] 
      ] 
    ], 
    ["Ritem1", 
     [ 
     "RRItem1", 
     [ 
      "Item1", 
      "Item2" 
      ] 
     ], 
     ["Item2"] 
    ] 
    ] 

recPrint(t,depth=0) 

生產(與您要求相同)

>>> 
Root 
- Ritem1 
    -- Item1 
    -- RRItem2 
    --- Item1 
    --- Item2 
- Ritem1 
    -- RRItem1 
    --- Item1 
    --- Item2 
    -- Item2