I created a function that will reverse a Linked List, but there is something weird going on, and I haven't been able to figure it out.
I am trying to edit the list in place to save space, so the method changes the original list object and doesn't return anything. Which means the last lines if the reverse_list
method are (variables renamed here for clarity):
original_first_node.val = new_first_node.val
original_first_node.next = new_first_node.next
But for some reason, the node chain on original_first_node.next
looks different than that of new_first_node.next
, and it's also cyclical now.
Here is some runnable code with a failing unit test (see the comments in the reverse_list
function):
import unittest
class Node(object):
def __init__(self, x):
self.val = x
self.next = None
def create_list(list):
if not list:
return None
sentinel = Node(None)
current = sentinel
for item in list:
current.next = Node(item)
current = current.next
return sentinel.next
def convert_list(head):
ret = []
if head:
current = head
while current:
ret.append(current.val)
current = current.next
return ret
def is_list_cyclic(head):
if not head:
return False
tortoise = hare = head
while hare.next and hare.next.next:
tortoise = tortoise.next
hare = hare.next.next
if tortoise == hare:
return True
return False
def reverse_list(head):
if not head or not head.next:
return
current = head
prev = None
while current:
static_next = current.next
current.next = prev
prev = current
current = static_next
# At this point, prev.next looks great
head.val = prev.val
head.next = prev.next
# head.next is cyclical now for some reason ??
class TestSuite(unittest.TestCase):
def test_reverse_list(self):
head = create_list([1, 2, 3, 4])
reverse_list(head)
self.assertFalse(is_list_cyclic(head))
self.assertEqual([4, 3, 2, 1], convert_list(head))
if __name__ == "__main__":
unittest.main()