面试题 02.06. 回文链表

编写一个函数,检查输入的链表是否是回文的。

 

示例 1:

输入: 1->2
输出: false 

示例 2:

输入: 1->2->2->1
输出: true 
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        # 使用list存储value

        stack = []
        while head:
            stack.append(head.val)
            head = head.next
        
        if len(stack) <= 1:
            return True

        reverse = stack[::-1]
        if stack == reverse:
            return True
        else:
            return False

 

你可能感兴趣的:(面试题 02.06. 回文链表)