Reverse Linked List

LeeoCode 206

"""
Sep 4, 2018
"""
# 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
        """
        """
        思路:
        a -> b -> c 
        1. 加上 tail 指標: tail = None
        None a -> b -> c
        2. 處理 node 前有甚麼事情需要做? 我們需要下個node位置
        cur = head
        head = cur.next
        cur.next = tail
        tail = cur
        """       
        tail = cur = None
        while head:
            cur = head
            head = cur.next           
            cur.next = tail
            tail = cur
        return cur

Last updated