小编给大家分享一下Python3怎么实现判断回文链表算法的示例,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!
问题:
请判断一个链表是否为回文链表。
方案一:指针法
class Solution:
def isPalindrome(self, head):
"""
判断一个链表是否是回文的,很自然的想法就是两个指针,一个指针从前往后走,一个指针从后往前走,判断元素值是否相同,这里要分几个步骤来进行求解:
1、找到链表长度的一半,用追赶法,一个指针一次走两步,一个指针一次走一步
2、将后一半数组转置
3、判断链表是否是回文链表
:type head: ListNode
:rtype: bool
"""
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
node = None
while slow:
nxt = slow.next
slow.next = node
node = slow
slow = nxt
while node and head:
if node.val != head.val:
return False
node = node.next
head = head.next
return True
方案二:列表法
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
res = []
cur = head
while cur:
res.append(cur.val)
cur = cur.next
return res == res[: : -1]
看完了这篇文章,相信你对“Python3怎么实现判断回文链表算法的示例”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。