I am looking to do it with Python. And I don\'t want to just print it in reverse, but actually reverse the given nodes. I have seen it done in other languages but had trouble fi
def reverse (item, tail = None):
next = item.next
item.next = tail
if next is None:
return item
else:
return reverse(next, item)
Using such a simple linked list implementation:
class LinkedList:
def __init__ (self, value, next = None):
self.value = value
self.next = next
def __repr__ (self):
return 'LinkedList({}, {})'.format(self.value, repr(self.next))
Example:
>>> a = LinkedList(1, LinkedList(2, LinkedList(3, LinkedList(4))))
>>> a
LinkedList(1, LinkedList(2, LinkedList(3, LinkedList(4, None))))
>>> b = reverse(a)
>>> b
LinkedList(4, LinkedList(3, LinkedList(2, LinkedList(1, None))))
>>> a # note that there is a new head pointer now
LinkedList(1, None)