Python3实现的判断回文链表算法示例
作者:zhenghaitian 时间:2021-04-10 05:53:25
本文实例讲述了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]
希望本文所述对大家Python程序设计有所帮助。
来源:https://blog.csdn.net/zhenghaitian/article/details/81025147
标签:Python3,回文链表,算法
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python中利用原始套接字进行网络编程的示例
2023-06-22 18:02:03
Python接单的过程记录分享
2022-05-24 13:33:23
![](https://img.aspxhome.com/file/2023/1/107281_0s.png)
python安装模块如何通过setup.py安装(超简单)
2023-06-13 00:46:30
![](https://img.aspxhome.com/file/2023/4/59294_0s.png)
Python实现扫码工具的示例代码
2022-07-06 06:06:36
JS不同加载方式下的window.onload
2009-05-21 18:09:00
![](https://img.aspxhome.com/file/UploadPic/20095/21/j200951902925-22s.gif)
python空值判断方式(if xxx和if xxx is None的区别及说明)
2022-04-01 20:18:42
Python3爬虫学习之爬虫利器Beautiful Soup用法分析
2021-04-13 07:01:50
![](https://img.aspxhome.com/file/2023/8/112168_0s.png)
asp日期 时间 星期函数使用方法详解
2007-09-21 17:38:00
windows环境中利用celery实现简单任务队列过程解析
2023-08-09 12:15:28
![](https://img.aspxhome.com/file/2023/1/102931_0s.png)
Oracle的数据字典技术简析
2010-07-20 13:03:00
Python元组的定义及使用
2021-06-30 01:24:40
Python 类属性与实例属性,类对象与实例对象用法分析
2023-03-12 01:43:03
![](https://img.aspxhome.com/file/2023/3/91903_0s.png)
Sql Server表死锁的解决方法分享
2011-09-01 19:08:00
[译]2009年海外Web设计风潮(上)
2009-01-23 09:21:00
![](https://img.aspxhome.com/file/UploadPic/up/3-2009webui.gif)
django 消息框架 message使用详解
2021-06-21 17:22:29
分面搜索(Faceted Search)
2009-07-31 12:44:00
![](https://img.aspxhome.com/file/UploadPic/20097/31/0907_facetedsearch_10-93s.jpg)
Python中的上下文管理器相关知识详解
2022-07-03 16:40:24
![](https://img.aspxhome.com/file/2023/2/95882_0s.jpg)
用python3教你任意Html主内容提取功能
2022-09-08 02:27:01
![](https://img.aspxhome.com/file/2023/2/115162_0s.gif)
Python tkinter三种布局实例详解
2022-11-28 11:23:44
![](https://img.aspxhome.com/file/2023/7/86417_0s.jpg)
python3 爬取图片的实例代码
2021-08-22 13:37:57