patternpythonMinor
Print linkedlist reversely
Viewed 0 times
reverselyprintlinkedlist
Problem
I'm working on the problem of print a linked list reversely without destruction. I'm wondering if any other better ideas, in terms of both time complexity improvement and space complexity improvement. I also welcome for code bugs and code style advice.
class LinkedListNode:
def __init__(self, value, nextNode):
self.value = value
self.nextNode = nextNode
def print_reverse(self):
if not self.nextNode:
print self.value
return
else:
self.nextNode.print_reverse()
print self.value
if __name__ == "__main__":
head = LinkedListNode('a', LinkedListNode('b', LinkedListNode('c', LinkedListNode('d', None))))
head.print_reverse()Solution
Code Style notes:
Other improvements:
With all the suggestions applied (except the docstrings):
As a side note, if you would be on Python 3.3+, this part:
can be rewritten using the generator delegation:
- follow PEP8 style guide, in particular:
- one empty between the class methods
- two empty lines after the class definition and before the next block
- use
print()function instead of a statement - this way you are staying compatible with the Python 3.x
- rename
nextNodetonext_node
- don't forget about the docstrings
Other improvements:
- you should probably explicitly inherit from object to have a new-style class (reference)
- instead of a
print_reverse(), how about you create a generator method that would yield nodes instead of printing - this can come out handy later when you would actually need to use the node values, not just have them on the console
With all the suggestions applied (except the docstrings):
class LinkedListNode(object):
def __init__(self, value, next_node):
self.value = value
self.next_node = next_node
def reverse_traversal(self):
if not self.next_node:
yield self.value
else:
for node in self.next_node.reverse_traversal():
yield node
yield self.value
if __name__ == "__main__":
head = LinkedListNode('a', LinkedListNode('b', LinkedListNode('c', LinkedListNode('d', None))))
for node in head.reverse_traversal():
print(node)As a side note, if you would be on Python 3.3+, this part:
for node in self.next_node.reverse_traversal():
yield nodecan be rewritten using the generator delegation:
yield from self.next_node.reverse_traversal()Code Snippets
class LinkedListNode(object):
def __init__(self, value, next_node):
self.value = value
self.next_node = next_node
def reverse_traversal(self):
if not self.next_node:
yield self.value
else:
for node in self.next_node.reverse_traversal():
yield node
yield self.value
if __name__ == "__main__":
head = LinkedListNode('a', LinkedListNode('b', LinkedListNode('c', LinkedListNode('d', None))))
for node in head.reverse_traversal():
print(node)for node in self.next_node.reverse_traversal():
yield nodeyield from self.next_node.reverse_traversal()Context
StackExchange Code Review Q#150561, answer score: 6
Revisions (0)
No revisions yet.