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.

share|improve this question
On Code Review we strictly help improve working code. Since your code has a "small problem," it doesn't work. So its off topic here. – Winston Ewert Oct 16 '12 at 12:04

closed as off topic by Glenn Rogers, palacsint, Brian Reichle, Winston Ewert Oct 16 '12 at 12:05

Questions on Code Review - Stack Exchange are expected to relate to code review request within the scope defined in the FAQ. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about closed questions here.

1 Answer

At a guess, are you doing something like:

print( obj.reverse_list( obj.head ) )

Since reverse_list doesn't explicitly return anything, it returns None, which is then printed out.

But I'm not convinced you're answering the question - the list isn't being reversed at all, only printed out as if it were. And you have a dangling <-

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.