翻轉一個單向鏈表。
注意點:
無例子:
輸入: 1->2->3
輸出: 3->2->1
非常基礎的一道題。前後兩個指針,把後指針指向的節點的next指向前節點,在此之前用一個臨時變量存儲後指針原來的後一個節點以保證能夠不斷更新前後指針的位置。最後不要忘記把原先的頭節點的next置為空,因為它現在是最後一個節點。
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def to_list(self):
return [self.val] + self.next.to_list() if self.next else [self.val]
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return None
prev = head
curr = prev.next
while curr:
next = curr.next
curr.next = prev
prev = curr
curr = next
head.next = None
return prev
if __name__ == "__main__":
n1 = ListNode(1)
n2 = ListNode(2)
n3 = ListNode(3)
n1.next = n2
n2.next = n3
r = Solution().reverseList(n1)
assert r.to_list() == [3, 2, 1]