如何遍历链表Python

2024-04-29 08:39:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找出如何使用递归在Python中遍历链表。

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

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

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

谢谢


Tags: none列表is链接mynotitemlist
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

试试这个。

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

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

reverce(n3)

你可以这样做:

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)

相关问题 更多 >