I have some code to reverse a LinkedList where I start with values a = [1,2,3,4,5] that when I do an assignment c = a.reverse() c is "None" while a is [5, 4, 3, 2, 1]. Why doesn't assignment work when calling a class method?
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, value):
if self.head is None:
self.head = Node(value)
return
node = self.head
while node.next:
node = node.next
node.next = Node(value)
def reverse(self):
if self.head is None:
return
curr = self.head
prev = None
while curr:
next = curr.next
curr.next = prev
prev = curr
curr = next
self.head = prev
print self.head.value
print self.head.next.value
print self.head.next.next.value
def __iter__(self):
node = self.head
while node:
yield node.value
node = node.next
def __repr__(self):
return str([v for v in self])
def reverse(linked_list):
new_list = LinkedList()
if linked_list is None:
return new_list
node = linked_list.head
new_list.head = node
while node:
old_head = new_list.head
curr = node
node = node.next
new_list.head = curr
new_list.head.next = old_head
return new_list
if __name__ == "__main__":
a = LinkedList()
b = [1,2,3,4,5]
for item in b:
a.append(item)
print(a)
c = a.reverse()
print(a)
print(c)