gpt4 book ai didi

python-3.x - 通过递归方式反向双向链表不在python中迭代

转载 作者:行者123 更新时间:2023-12-01 05:50:16 24 4
gpt4 key购买 nike

我如何通过递归为双链表编写反向函数。我已经在 python 中使用递归和重写来引用问题反向双链表,但它使我进入无限循环,所以我重写了逻辑,但我有点丢失了上一个点

class Node:
def __init__(self, data, prev=None, nxt=None):
self.val = data
self.prev = prev
self.next = nxt


class DoublyLinkedList:
def __init__(self, head):
self.head = head

def print_list(self):
cur = self.head
while cur is not None:
print(cur.val)
cur = cur.next

def reverse(self):
if self.head is None or self.head.next is None: return self.head
cur = self.head
def reverse_node(node):
if node is None: return
if node.next is None:
node.prev = None
return node
new_head = reverse_node(node.next)
new_node = node.next
tmp = new_node.next
new_node.prev = tmp
new_node.next = node
node.next = None
return new_head
self.head = reverse_node(cur)

a = Node(1, prev=None)
b = Node(2, prev=a)
c = Node(3, prev=b)
d = Node(4, prev=c)
a.next = b
b.next = c
c.next = d
dll = DoublyLinkedList(a)
dll.print_list()
dll.reverse()
dll.print_list()

最佳答案

我所做的就是在最后添加一些打印输出,看看是什么。在我看来,您的代码似乎符合您的期望。后 reverse()功能头部似乎明确指向d而不是 a

class Node:
def __init__(self, data, prev=None, nxt=None):
self.val = data
self.prev = prev
self.next = nxt


class DoublyLinkedList:
def __init__(self, head):
self.head = head

def print_list(self):
cur = self.head
while cur is not None:
print(cur.val)
cur = cur.next

def reverse(self):
if self.head is None or self.head.next is None: return
cur = self.head

def reverse_node(node):
if node is None: return node
node.next, node.prev = node.prev, node.next
if node.prev is None: return node
return reverse_node(node.prev)

self.head = reverse_node(cur)

a = Node(1, prev=None)
b = Node(2, prev=a)
c = Node(3, prev=b)
d = Node(4, prev=c)
a.next = b
b.next = c
c.next = d
dll = DoublyLinkedList(a)
print("Head: ",dll.head.val)
dll.print_list()
dll.reverse()
print()
print("Head: ",dll.head.val)
dll.print_list()
print("Is the head at a? ",dll.head is a)
print("Is the head at d? ",dll.head is d)

输出:
Head:  1
1
2
3
4

Head: 4
4
3
2
1
Is the head at a? False
Is the head at d? True

关于python-3.x - 通过递归方式反向双向链表不在python中迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55231846/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com