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

python---連結串列反轉

"""
Definition of ListNode

class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""


class Solution:
    """
    @param: node: n
    @return: The new head of reversed linked list.
    """

    #最後的返回結點一定是元連結串列的最後一個尾結點,判定尾結點的方法
    #就是結點的下一位為None,然後每次在翻轉的時候需要先儲存後一位,
    #然後當前指向前一節點,由於翻轉後原陣列的第一位的下一位是None
    #所以最開始的時候pre前結點設定為None
    def reverse(self, node):
        # write your code here
        res = None
        pre = None
        cur = node
        while cur:
            cur_next = cur.next
            cur.next  = pre
            pre = cur
            if not cur_next:
                res = cur

            cur = cur_next
        return res: