Linked Lists
Write a function that takes a linked list and changes the list so that the nodes are in the reverse order.
We’ve provided a Node class:
class Node(object):
"""Class in a linked list."""
def __init__(self, data, next=None):
self.data = data
self.next = next
We’ve also provided a LinkedList class with a helper method for printing the list (this is used by our tests and is useful for debugging):
class LinkedList(object):
"""Linked list."""
def __init__(self, head=None):
self.head = head
def as_string(self):
"""Represent data for this list as a string.
>>> LinkedList(Node(3)).as_string()
'3'
>>> LinkedList(Node(3, Node(2, Node(1)))).as_string()
'321'
"""
out = []
n = self.head
while n:
out.append(str(n.data))
n = n.next
return "".join(out)
We’ve also provided the start of a reverse_linked_list_in_place function:
def reverse_linked_list_in_place(lst):
"""Given linked list, reverse the nodes in this linked list in place."""
Complete this function.
For example:
>>> ll = LinkedList(Node(1, Node(2, Node(3))))
>>> reverse_linked_list_in_place(ll)
>>> ll.as_string()
'321'