一文搞定链表面试题系列之二 —— Leetcode234. Palindrome Linked List回文链表\

版权声明:博客为作者平时学习备忘,参考资料已在文尾列出一并表示感谢。如若转载,请列明出处。 https://blog.csdn.net/woai8339/article/details/84801509

链表荟萃二:

回文链表

题目:回文链表给定一个链表,判断该链表是否是回文链表,要求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、回文链表

猜你喜欢

转载自blog.csdn.net/woai8339/article/details/84801509