题目
请编写一个函数,检查链表是否为回文。
给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。
测试样例:
{1,2,3,2,1}
返回:true
{1,2,3,2,3}
返回:false
思路
定义一个stack,存储链表的值,两次遍历。
代码
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Palindrome:
def isPalindrome(self, pHead):
# write code here
stack = []
p = pHead
while p:
stack.append(p.val)
p = p.next
p = pHead
while p:
if p.val != stack[-1]:
return False
stack.pop(-1)
p = p.next
return True