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:
while not l.IsEmpty:
nl = Node(l.value,nl)
l = l.tail
each new nl
is the tail of the next one. So 1 is the tail for 2, and so on.
Think about what is happening in the first while
loop. It builds a new list in reverse. We start with 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. 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.