本文實例講述了Python3實現(xiàn)的判斷回文鏈表算法。分享給大家供大家參考,具體如下:
問題:
請判斷一個鏈表是否為回文鏈表。
方案一:指針法
class Solution: def isPalindrome(self, head): """ 判斷一個鏈表是否是回文的,很自然的想法就是兩個指針,一個指針從前往后走,一個指針從后往前走,判斷元素值是否相同,這里要分幾個步驟來進行求解:1、找到鏈表長度的一半,用追趕法,一個指針一次走兩步,一個指針一次走一步2、將后一半數(shù)組轉(zhuǎn)置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 = Noneclass Solution: def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ res = [] cur = head while cur: res.append(cur.val) cur = cur.next return res == res[: : -1]
希望本文所述對大家Python程序設(shè)計有所幫助。
新聞熱點
疑難解答
圖片精選