版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
题目描述
请编写一个函数,检查链表是否为回文。
给定一个链表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
class Palindrome:
def isPalindrome(self, pHead):
tmp_head=pHead
new_head,tmp=None,None
if not pHead or not pHead.next :
return False
while tmp_head :
tmp=tmp_head.next
tmp_head.next=new_head
new_head=tmp_head
tmp_head=tmp
while pHead :
if pHead.val==new_head.val :
pHead=pHead.next
new_head=new_head.next
pass
else :
return False
return True
思路:笨方法,获取该链表的反转链表,然后两个链表再逐一比较。程序没问题,通过了百分之70左右的测试样例,后面可能是运行时间太长了,超过了时间限制。。。
下面这段代码是通过所有测试样例的。
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Palindrome:
def isPalindrome(self, pHead):
str1=''
str2=''
while pHead :
str1=str1+str(pHead.val)
pHead=pHead.next
str2=str1[::-1]
if str1==str2 :
return True
return False
思路:先将链表中的数据取出成为字符串,然后获取反转之后的字符串,判断两串是否相等。
还有人是像下面那样写的,运用了栈的知识(pop),从中间开始分别向左右两边开始比较,如果链表长度为奇数,会主动跳过中间的数(因为在这种情况下不用比较中间的数)
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Palindrome:
def isPalindrome(self, pHead):
if not pHead or not pHead.next :
return False
stack=[]
slow=pHead
fast=pHead.next
stack.append(slow.val)
while True :
if not fast.next :
mid=slow.next
break
elif fast.next and not fast.next.next :
mid=slow.next.next
break
slow=slow.next
fast=fast.next.next
stack.append(slow.val)
while stack and mid :
top=stack.pop()
if top != mid.val :
return False
mid=mid.next
return True
最后提一下个人觉得这两篇博客讲链表反转还是不错的:
https://blog.csdn.net/weixin_39561100/article/details/79818949