leetcode 迴文鏈表 python3

class Solution:
    def isPalindrome(self, head):
        """
        判斷一個鏈表是否是迴文的,很自然的想法就是兩個指針,一個指針從前往後走,一個指針從後往前走,判斷元素值是否相同,這裏要分幾個步驟來進行求解:
1、找到鏈表長度的一半,用追趕法,一個指針一次走兩步,一個指針一次走一步
2、將後一半數組轉置
3、判斷鏈表是否是迴文鏈表
        :type head: ListNode
        :rtype: bool
        """
        slow = fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
 
        node = None
        while slow:
            nxt = slow.next
            slow.next = node
            node = slow
            slow = nxt
 
        while node and head:
            if node.val != head.val:
                return False
            node = node.next
            head = head.next
        return True
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
 
class Solution:
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        nums = []
        while head:
            stack.append(head.val)
            head = head.next
        return nums == nums[::-1]   

https://blog.csdn.net/zhenghaitian/article/details/81025147

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章