收益率值不会在递归中返回

2024-04-25 17:05:40 发布

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

我试图编写一个迭代器,从最后一个节点到头节点,以相反的方式返回链表中的数据。你知道吗

但由于某些原因,只有我们返回的第一个值,即在第一个递归级别返回的值。你知道吗

=============代码===========

class Node:

    def __init__(self ,data ,next=None):

        self.data = data
        self.next = next

def foo(head):

    if head.next is None:
        yield head.data
    else:
        foo(head.next)
        yield head.data

====================================

head = Node('A',Node("B", Node("C")))

for x in foo(head):

    print(x)

==========结果===========
A

=======应为========

A B类 C级


Tags: 数据selfnonenodedata节点foodef
1条回答
网友
1楼 · 发布于 2024-04-25 17:05:40

下面的方法用于打印前向节点列表和后向节点列表。你知道吗

节点类:

>>> class Node:
...     def __init__(self, data=None, next=None):
...             self.data = data
...             self.next  = next
...     def __str__(self):
...             return str(self.data)

包含多个节点的列表

>>> node1 = Node('A')
>>> node2 = Node('B')
>>> node3 = Node('C')

链接节点,第一个节点表示第二个节点,第二个节点表示第三个节点,第三个节点表示无

>>> node1.next = node2
>>> node2.next = node3

打印转发列表

>>> def print_list(node):
...     while node:
...             print(node),
...             node = node.next
...     print
...
>>> print_list(node1)
A
B
C

向后打印列表

>>> def print_backward(list):
...     if list == None: return
...     head = list
...     tail = list.next
...     print_backward(tail)
...     print(head),
...
>>> print_backward(node1)
C
B
A

更多详情please refer

相关问题 更多 >

    热门问题