我一直在学习链表,用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)
编辑:我的输出:
^{pr2}$
您的
swapPairsI
函数正在返回链接列表的新的head
。 您需要相应地更新:或者更好的是,您应该更改您的
^{pr2}$swapPairsI
函数,使其不必将节点作为参数:在这种情况下,您只需拨打:
相关问题 更多 >
编程相关推荐