[英]How does this print a reversed linked list
How does this piece of code print a linked list reversed? 这段代码如何打印反向链接列表? I'm pretty curious how the new list comes to this way.
我很好奇新清单是如何出现的。
class Empty:
def __init__ (self):
self.IsEmpty = True
Empty = Empty()
class Node:
def __init__ (self,value,tail):
self.IsEmpty = False
self.value = value
self.tail = tail
l = Node(1,Node(2,Node(3,Node(4,Empty))))
c = l
nl = Empty
while not l.IsEmpty:
nl = Node(l.value,nl)
l = l.tail
while not nl.IsEmpty:
print(nl.value)
nl = nl.tail
It doesn't print reversed, nl
is built reversed: 它不打印逆转,
nl
建逆转:
while not l.IsEmpty:
nl = Node(l.value,nl)
l = l.tail
each new nl
is the tail of the next one. 每个新的
nl
是下一个的尾部。 So 1 is the tail for 2, and so on. 所以1是2的尾巴,依此类推。
Think about what is happening in the first while
loop. 想想第一个
while
循环中发生了什么。 It builds a new list in reverse. 它会反向建立一个新列表。 We start with
Empty
. 我们从
Empty
开始。 Then each iteration: 然后每次迭代:
new_list = Node(l.current_value, Node(l.previous_value))
Where previous_value
is the value encountered first while iterating through the original list. 其中
previous_value
是遍历原始列表时首先遇到的值。 So, this could be expanded to: 因此,可以将其扩展为:
Node(l.last_value, Node(l.second_to_last, Node(...Node(l.first_value, Empty)...)))
It builds a forwards list 它建立一个转发列表
l = Node(1,Node(2,Node(3,Node(4,Empty))))
Then builds a backwards list from that forwards list 然后从该转发列表构建一个向后列表
nl = Empty
while not l.IsEmpty:
nl = Node(l.value,nl)
l = l.tail
Then prints that list out in order, which is the reverse of the first list. 然后按顺序打印该列表,这与第一个列表相反。
This is a pretty convoluted way of doing things. 这是一种非常复杂的处理方式。 Better would be something recursive, like:
最好是递归的,例如:
def printer(curr):
if curr.isEmpty:
return
printer(curr.tail)
print(curr.value)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.