gpt4 book ai didi

python - 在 Python 的链表中交换对,一个链接消失了?

转载 作者:太空宇宙 更新时间:2023-11-04 02:40:37 25 4
gpt4 key购买 nike

我一直在学习链表,用 Python 实现链表比我预期的要容易。但是,当解决“在链表中交换对”的问题时,出于某种原因,我的第二个链接在交换过程中消失了。我一直盯着这个看很久,并尝试了我在网上找到的不同解决方案。他们都得到相同的结果,这表明我的问题出在列表本身的实现上。或者我在某个地方犯了一个我看不到的愚蠢错误!如果有一双新鲜的眼睛,我将不胜感激。我做错了什么?

class Node:
def __init__(self, val):
self.value = val
self.next = None

class LinkedList:
def __init__(self, data):
self.head = Node(data)

def printList(self, head):
while head:
print("->" , head.value)
head = head.next;

def swapPairsR(self, node): # recursive
if node is None or node.next is None:
return node
ptrOne = node
ptrTwo = node.next
nextPtrTwo = ptrTwo.next

# swap the pointers here at at the rec call
ptrTwo.next = node
newNode = ptrTwo

ptrOne.next = self.swapPairsR(nextPtrTwo)
return newNode

def swapPairsI(self, head): # iterative
prev = Node(0)
prev.next = head
temp = prev

while temp.next and temp.next.next:
ptrOne = temp.next
ptrTwo = temp.next.next

# change the pointers to the swapped pointers
temp.next = ptrTwo
ptrOne.next = ptrTwo.next
ptrTwo.next = ptrOne
temp = temp.next.next

return prev.next

thisLList = LinkedList(1)
thisLList.head.next = Node(2)
thisLList.head.next.next = Node(3)
thisLList.head.next.next.next = Node(4)
thisLList.head.next.next.next.next = Node(5)
thisLList.printList(thisLList.head)
print("--------------")
thisLList.swapPairsI(thisLList.head)
thisLList.printList(thisLList.head)

编辑:我的输出:

-> 1
-> 2
-> 3
-> 4
-> 5
--------------
-> 1
-> 4
-> 3
-> 5

最佳答案

您的 swapPairsI 函数正在返回链表的新 head。您需要相应地更新它:

thisLList.head = thisLList.swapPairsI(thisLList.head)

或者更好的是,您应该更改 swapPairsI 函数,这样它就不必将节点作为参数:

def swapPairsI(self): # iterative
prev = Node(0)
prev.next = self.head
temp = prev

while temp.next and temp.next.next:
ptrOne = temp.next
ptrTwo = temp.next.next

# change the pointers to the swapped pointers
temp.next = ptrTwo
ptrOne.next = ptrTwo.next
ptrTwo.next = ptrOne
temp = temp.next.next

self.head = prev.next

在这种情况下,您可以简单地调用:

thisLList.swapPairsI()

关于python - 在 Python 的链表中交换对,一个链接消失了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46648779/

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