1. 程式人生 > >python 反轉連結串列 LeetCode

python 反轉連結串列 LeetCode

反轉一個單鏈表。

示例:

輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL

程式碼示例:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseList(self, head, pre=None):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        #迭代:迴圈?
        while head:
            cur = head
            head = head.next
            cur.next = pre
            pre = cur
        return pre