如何判断一个单链表是否为回文
链接:https://www.nowcoder.com/questionTerminal/baefd05def524a92bcfa6e1f113ed4f0
来源:牛客网
请编写一个函数,检查链表是否为回文。
给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。
测试样例:
{1,2,3,2,1}
返回:true
{1,2,3,2,3}
返回:false
思路:先找到中间节点,然后将后面倒置,再两个链表比对
# -*- coding:utf-8 -*- class ListNode: def __init__(self, x): self.val = x self.next = None def isPalindrome(pHead): if not pHead: return False mid=findMidNode(pHead) s=LinkReverse(mid) p=pHead while s and p: if s.val!=p.val: return False p=p.next s=s.next return True def findMidNode(pHead): p=pHead q=pHead.next while q: #if q.next and (not q.next.next): # if not q.next: break p=p.next if q.next: try: q=q.next.next except: q=q.next return p def LinkReverse(pHead): q=pHead.next pHead.next=None while q: s=q q=q.next s.next=pHead.next pHead.next=s return s pHead=ListNode(1) node2=ListNode(2) node3=ListNode(3) node4=ListNode(2) node5=ListNode(1) pHead.next=node2 node2.next=node3 node3.next=node4 node4.next=node5 print isPalindrome(pHead)