I am trying to implement reverse linked list using recursion:
class node:
def __init__(self, data=None):
self.data=data
self.next_node=None
class linked_list:
def __init__(self):
self.head=node()
def push(self, data):
new_node=node(data)
cur_node=self.head
while(cur_node.next_node!=None):
cur_node=cur_node.next_node
cur_node.next_node=new_node
def display(self):
elems=[]
cur_node=self.head
print('Display:')
# print(cur_node)
# print(cur_node.next_node)
# print(cur_node.data)
while(cur_node.next_node!=None):
cur_node=cur_node.next_node
elems.append(cur_node.data)
print(elems)
def lenth(self):
i=0
cur_node=self.head
while(cur_node.next_node!=None):
last_node=cur_node
cur_node=cur_node.next_node
i+=1
print(i)
def reversell_rec(self, node):
# print("Recursive")
cur_node = node
# print(cur_node)
# print(cur_node.next_node)
# print(cur_node.data)
if (cur_node.next_node == None):
self.head.next_node = cur_node
return
self.reversell_rec(cur_node.next_node)
temp=cur_node.next_node
temp.next_node = node
node.next_node = None
ll=linked_list()
ll.push(1)
ll.push(2)
ll.display()
ll.reversell_rec(ll.head)
ll.display()
I get the output:
Display: #Display before recursion
[1, 2]
Display: #Display after recursion
[]
I tried different ways of printing them out using objects but somehow it self.head.next_node changes back to "None" even though I am assigning the last node to self.head.next_node to the last node. What is causing the change? Can you please help?
Edit:
def reversell_rec(self, node):
# print("Recursive")
cur_node = node
# print(cur_node)
# print(cur_node.next_node)
# print(cur_node.data)
if (cur_node.next_node == None):
self.head.next_node = cur_node
return
self.reversell_rec(cur_node.next_node)
if(cur_node!=self.head):
temp = cur_node.next_node
temp.next_node = cur_node
cur_node.next_node = None '