如何遍历Python中的链表

9

我正在尝试通过递归在Python中遍历链表。

我知道如何使用常见的循环(例如for循环和while循环)遍历链表:

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

我想知道如何将这个循环转换为递归步骤。
谢谢。

递归在Python中不是一个理想的解决方案,因为您将无法超过列表中的第1000个元素。 - Eric
1
提示:先打印第一项,然后打印其余的项。 - Eric
@Eric。嗯,好的...但是当我打印剩下的部分时...它会给我一个内存地址。 - Andre
1
“print the rest”需要打印链表。但是您刚刚编写了一个知道如何打印链表的函数。因此,调用该函数而不是“print”。 - Eric
你所指的函数应该是 item。因为 item 函数可以显示链表元素的值。 - Andre
3个回答

7
您可以这样做:
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)

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)

0

看起来你的链表有两种部分。你有列表节点,带有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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接