24反转链表

定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。

class LinkNode(object):
    def __init__(self, val, nxt):
        self.value = val
        self.next = nxt

class Solution(object):
    def ReverseList(self, pHead):
        if not pHead or not pHead.next:
            return pHead

        probe = pHead
        pPrev = None
        while probe:
            pNext, probe.next, pPrev = probe.next, pPrev, probe
            # pNext = probe.next
            # probe.next = pPrev
            # pPrev = probe
            probe = pNext
        return pPrev

if __name__ == '__main__':
    a = LinkNode(1, None)
    b = LinkNode(2, a)
    c = LinkNode(3, b)
    
    d = LinkNode(0, None)
    e = LinkNode(5, d)
    answer = Solution()
    
    assert answer.ReverseList(None) is None
    assert answer.ReverseList(a).value == a.value
    rev_c = answer.ReverseList(c)
    assert rev_c.value == a.value
    while rev_c.next:
        rev_c = rev_c.next
    assert rev_c.value == c.value
    assert answer.ReverseList(e).value == 0

你可能感兴趣的:(24反转链表)