Problem: create a linked list and reverse the list appending with '<-'.
Example, if the linked list is [1,2,3,4,5,6]
, so the result is 5 <- 4 <- 3 <- 2 <- 1
.
Here is the code
class Node(object):
def __init__(self, data, next=None):
self.data = data
self.next = next
def __str__(self):
return str(self.data)
class LinkedList(object):
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def create_node(self, data):
new_node = Node(data)
if self.tail:
self.tail.next = new_node
else:
self.head = new_node
self.tail = new_node
self.length += 1
def head(self):
return self.head
def tail(self):
return self.tail
def reverse_list(self, node=None):
if node == None : return
head = node
tail = node.next
# add condition to remove None type
self.reverse_list(tail)
print head, '<-',
def __iter__(self):
node = self.head
while node:
yield node
node = node.next
else:
raise StopIteration
def __repr__(self):
return ('LinkedList:[' +','.join([str(node) for node in self]) +']')
Usage:
>obj = LinkedList()
>for i in range(1,6):
> obj.create_node(i)
Would like to get feedback. The code works but I noticed a small problem. After reversing the list it appends "None type" with the reversed list.
So the result becomes 5 <- 4 <- 3 <- 2 <- 1 <- None
instead of 5 <- 4 <- 3 <- 2 <- 1
. I think the check should be somewhere in the place where I commented #add condition to remove None type
. But I was not able to handle the condition correctly and not sure why is this None type is adding to the reversed list.