Description

输入一个链表,反转链表后,输出新链表的表头。

Solutions

class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        if not pHead:
            return None
        if not pHead.next:
            return pHead
        prev = pHead
        prev.next = None
        pHead = pHead.next
        while pHead:
            if not pHead.next:
              	pHead.next = prev
                return pHead
            next_tmp = pHead.next
            pHead.next = prev
            prev = pHead
            pHead = next_tmp
        
        return prev

上述是我写的错误代码,虽然在切换时思路是对的,但是因为直接在原来的指针上进行操作,所以弄出了很多问题,导致在返回时一会儿返回 pHead,一会儿返回 prev,于是剪不断理还乱,甚是恼人。多建立一个指向返回的链表结点就他喵地方便和清楚好多!

class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # 不要在原来的链表头上做迭代的切换操作,会很乱!
        pNode = pHead
        pPrev = None
        pReverseNode = None
        
        while pNode:
            pNext = pNode.next
            if not pNext:
              	pReverseNode = pNode
            pNode.next = pPrev
            pPrev = pNode
            pNode = pNext
        
        return pReverseNode

切记不要再原来那个链表头做任何操作!!!!

References

  1. 016. 反转链表