题目描述
对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。
给定一个链表的头指针A,请返回一个bool值,代表其是否为回文结构。保证链表长度小于等于900。
测试样例:
1->2->2->1
返回:true
简单题,判断是否是回文串即可
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class PalindromeList:
def chkPalindrome(self, A):
# write code here
res = []
while A:
res.append(A.val)
A = A.next
n = len(res)
x = 0
y = n - 1
while True:
if x >= y:
return True
if res[x] != res[y]:
return False
x += 1
y -= 1