我正在尝试使用递归实现反向链表:
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()
我得到了输出:
Display: #Display before recursion
[1, 2]
Display: #Display after recursion
[]
我尝试了使用对象打印出来的不同方法,但不知何故,self.head.next_node变回“无”,即使我将最后一个节点分配给self.head.next_node到最后一个节点。是什么导致了变化?你能帮忙吗?
编辑:
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 '
答案 0 :(得分:0)
这看起来很可逆。如果你的意思是这样做,那么基本的想法是通过向后累积来构造一个反向。
def reversell_rec(self):
def rev_node(n, acc):
if n is None: return acc
nxt = n.next_node
n.next_node = acc
return rev_node(nxt, n)
self.head = rev_node(self.head, None)
但老实说,如果你在while循环中执行它会变得更容易,如果它是可变的。
答案 1 :(得分:0)
递归的基本条件是跳过其中一个元素。您正在执行self.head.next_node=cur_node
而不是仅将self.head
本身分配给最后一个元素。
我对reversell_rec
函数进行了一些更改:
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 = cur_node
return
self.reversell_rec(cur_node.next_node)
temp=cur_node.next_node
temp.next_node = cur_node
cur_node.next_node = None
因为您使用过"无"我必须改变display
功能:
def display(self):
elems=[]
cur_node=self.head
print('Display:')
# print(cur_node)
# print(cur_node.next_node)
# print(cur_node.data)
if self.head.data!=None:
while(cur_node.next_node!=None):
elems.append(cur_node.data)
cur_node=cur_node.next_node
else:
cur_node=cur_node.next_node
while(cur_node!=None):
elems.append(cur_node.data)
cur_node=cur_node.next_node
print(elems)