一文搞定連結串列面試題系列之二 —— Leetcode234. Palindrome Linked List迴文連結串列\
阿新 • • 發佈:2018-12-05
連結串列薈萃二:
迴文連結串列
題目:迴文連結串列給定一個連結串列,判斷該連結串列是否是迴文連結串列,要求O(n)
時間複雜度,O(1)
空間複雜度。
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
Example 2:
Input: 1->2->2->1
Output: true
列表解法
O(n)
時間複雜度,O(n)
# 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 """ result = [] cur = head while(cur): result.append(cur.val) cur = cur.next return result == result[::-1] #Note:result = [] result == result.reverse() --> False
Ref:
1、迴文連結串列