题目:
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
思路:回文链表反转前后肯定一致
代码:
# 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:
#回文链表反转前后需一致
L=[]
last=None
if head is None :
return True
while head:
L.append(head.val)
tmp=head.next
head.next=last
last=head
head=tmp
return L==L[::-1]