LeetCode 反轉連結串列【python】
阿新 • • 發佈:2019-02-05
反轉一個單鏈表。
示例:
輸入: 1->2->3->4->5->NULL 輸出: 5->4->3->2->1->NULL
進階:
你可以迭代或遞迴地反轉連結串列。你能否用兩種方法解決這道題?
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None or head.next == None:
return head
pre = None
cur = head
h = head
while cur:
h = cur
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return h