【问题标题】:How to traverse Linked-Lists Python如何遍历链表 Python
【发布时间】:2014-12-14 06:07:23
【问题描述】:

我试图弄清楚如何使用 递归 在 Python 中遍历链表。

我知道如何使用常见循环遍历链表,例如:

 item_cur = my_linked_list.first
       while item_cur is not None:
           print(item_cur.item)
           item_cur = item_cur.next  

我想知道如何将这个循环变成递归步骤。

谢谢

【问题讨论】:

  • 递归在 python 中不是一个理想的解决方案,因为你将无法越过列表中的第 1000 个元素
  • 提示:打印第一项,然后打印其余的
  • @Eric。嗯好吧..但是当我打印其余部分时..它给了我一个内存地址。
  • print the rest 需要打印一个链表。但是您刚刚编写了一个知道如何打印链表的函数。所以叫它而不是print
  • 你指的功能是item,我想。因为 item 揭示了链表中元素的值。

标签: python loops recursion linked-list


【解决方案1】:

试试这个。

class Node:
    def __init__(self,val,nxt):
        self.val = val
        self.nxt = nxt  
def reverse(node):
    if not node.nxt:
        print node.val
        return 
    reverse(node.nxt)
    print node.val

n0 = Node(4,None)
n1 = Node(3,n0)
n2 = Node(2,n1)
n3 = Node(1,n2)

reverse(n3)

【讨论】:

    【解决方案2】:

    你可以这样做:

    def print_linked_list(item):
        # base case
        if item == None:
            return
        # lets print the current node 
        print(item.item)
        # print the next nodes
        print_linked_list(item.next)
    

    【讨论】:

      【解决方案3】:

      看起来你的链表有两种部分。您有列表节点,具有 nextitem 属性,以及具有指向 first 节点的属性的包装器对象。要递归打印列表,您需要两个函数,一个用于处理包装器,另一个用于对节点进行递归处理。

      def print_list(linked_list):               # Non-recursive outer function. You might want
          _print_list_helper(linked_list.first)  # to update it to handle empty lists nicely!
      
      def _print_list_helper(node):              # Recursive helper function, gets passed a
          if node is not None:                   # "node", rather than the list wrapper object.
              print(node.item)
              _print_list_helper(node.next)      # Base case, when None is passed, does nothing
      

      【讨论】:

        猜你喜欢
        • 2013-10-14
        • 1970-01-01
        • 1970-01-01
        • 2017-09-03
        • 1970-01-01
        相关资源
        最近更新 更多