剣指offer 16反転チェーンテーブル(python 3.6)
3ポインタ法を採用し、テストを備えています.
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