1. 程式人生 > >【LeetCode 簡單題】63-迴文連結串列

【LeetCode 簡單題】63-迴文連結串列

宣告:

今天是第63道題。請判斷一個連結串列是否為迴文連結串列。以下所有程式碼經過樓主驗證都能在LeetCode上執行成功,程式碼也是借鑑別人的,在文末會附上參考的部落格連結,如果侵犯了博主的相關權益,請聯絡我刪除

(手動比心ღ( ´・ᴗ・` ))

正文

題目:請判斷一個連結串列是否為迴文連結串列。

示例 1:

輸入: 1->2
輸出: false

示例 2:

輸入: 1->2->2->1
輸出: true

進階:
你能否用 O(n) 時間複雜度和 O(1) 空間複雜度解決此題?

解法1。用快慢指標找到連結串列中點(slow最後指向的就是中部),然後讓slow指向的後半部分連結串列逐個與前半部分的節點值相比較,如果一直能相等遍歷到結束,就返回True,程式碼如下。

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

class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if not head or not head.next:
            return True
        fast = slow = head
        while(fast.next and fast.next.next):
            slow = slow.next
            fast = fast.next.next
        
        slow = slow.next
        slow = self.reverseList(slow)

        while slow:
            if slow.val != head.val:
                return False
            slow = slow.next
            head = head.next
        return True

    def reverseList(self,head):
        new_head = None
        while head:
            p = head
            head = head.next
            p.next = new_head
            new_head = p
        return new_head
            

結尾

解法1:https://blog.csdn.net/coder_orz/article/details/51306985