2017-10-09 19 views
1

我一直在学习链表,并且在python中实现一个比我想象的要容易。但是,当它解决了“在链表中交换对”的问题时,出于某种原因,我的第二个链接在交换过程中消失了。我一直在盯着这个世界,尝试不同的解决方案,我在网上找到。他们都得到相同的结果,这表明我的问题是与列表本身的实施。或者我在某个地方发现了一个我看不见的愚蠢错误!我会感激一双新鲜的眼睛。我做错了什么?在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 

回答

2

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() 
+0

哦,我的天啊,我什至没有想到这一点。呻吟!谢谢,当然这也是我的递归函数“错误”。 – dgBP