1. 程式人生 > >python實現單鏈表翻轉

python實現單鏈表翻轉

tro color ane hal data 鏈表翻轉 you 挑戰 clas

題目描述:

翻轉一個鏈表

您在真實的面試中是否遇到過這個題? Yes

樣例

給出一個鏈表1->2->3->null,這個翻轉後的鏈表為3->2->1->null

挑戰

在原地一次翻轉完成

題目分析:

在原地一次翻轉完成

循環head鏈表,將鏈表中的元素從表頭依次取出指向新鏈表即可。

源碼:

"""
Definition of ListNode
 
class ListNode(object):
 
    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""
class Solution:
    """
    @param head: The first node of the linked list.
    @return: You should return the head of the reversed linked list.
                  Reverse it in-place.
    """
    def reverse(self, head):
        # write your code here
        if head is None: return None
        p = head
        cur = None
        pre = None
        while p is not None:
            cur = p.next
            p.next = pre
            pre = p
            p = cur
        return pre

python實現單鏈表翻轉