1. 程式人生 > >【leetcode】迴文連結串列(Palindrome Linked List)【python】三種方法

【leetcode】迴文連結串列(Palindrome Linked List)【python】三種方法

題目連結
在這裡插入圖片描述

時間複雜度O(N),空間複雜度O(N)

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

def str_isPalindrome(nums, length):
    i, j = 0, length - 1
    while i != j:
        if nums[i] != nums[j]:
            return False
        if i == length / 2:
            return True
i += 1 j -= 1 return True class Solution: def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ #腦殘辦法,直接將連結串列裡面的資料放入陣列中 string = '' j = head if j == None: return True index =
0 nums = [0] * 100000 while j != None: nums[index] = j.val index += 1 j = j.next return str_isPalindrome(nums, index)

## 時間複雜度O(N),空間複雜度O(N/2) ##

1.這裡使用了快慢指標,快慢指標典型的應用就是判斷連結串列是否存在環,另外一個應用就是找出連結串列的中位數,這個地方就是使用快慢指標來尋找連結串列的中位數
2.另外使用棧來存取前半段的數,使用list.insert()方法,使用陣列來模擬棧

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if head == None or head.next == None:
            return True
        slow = fast = head #定義快慢指標來確定連結串列的中點
        list = []
        while fast and fast.next:
            list.insert(0, slow.val) #使用佇列來模擬棧
            slow = slow.next
            fast = fast.next.next
        if fast:
            slow = slow.next  #有奇數個節點,忽略
        for val in list:
            if val != slow.val:
                return False
            slow = slow.next
        return True

## 時間複雜度O(N),空間複雜度O(1) ##

1. 採用快慢指標來找到連結串列中點
2. 找到中點之後,採用空間複雜度O(1)的反轉連結串列的演算法,將連結串列反轉,需要注意的是,反轉過程中語句的順序,head = head.next一定要在第二句,而不是最後,要不然就斷鏈了,因為p指向了head更改p相當於更改了head,當head指向next之後,才能更改p

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def ReverseList(self, head):
        new_head = None
        while head:
            p = head
            head = head.next
            p.next = new_head
            new_head = p
            #head = head.next
        return new_head

    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        slow = fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        if fast:
            slow = slow.next
        new_head = self.ReverseList(slow)
        while new_head:
            if head.val != new_head.val:
                return False
            head = head.next
            new_head = new_head.next
        return True