class node:
def __init__(self, data = None):
self.data = data
self.next = None
class linked_list:
def __init__(self):
self.head = node()
This is how I initialize my LinkedList data structure in python.
After I append some nodes, by doing
my_list.append(1)
my_list.append(2)
my_list.append(3)
my_list.append(4)
and display it using the function that I wrote,
def display(self):
elems = []
curr = self.head
while curr.next != None:
curr = curr.next
elems.append(curr.data)
print(elems)
It prints out [1, 2, 3, 4]
which seems fine.
However, when I try to reverse it by using the function below
def reverseList(self):
curr = self.head
prev = None
while curr != None:
curr.next = prev
prev = curr
curr = curr.next
self.head = prev
It gives me an empty linkedList []
. If I draw the LinkedList on a paper, it seems fine and I don't see what I am doing wrong.