题目

请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false

示例 2:

输入: 1->2->2->1
输出: true

进阶:

你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

解答

两种方法:

  • 遍历链表,用数组存值,再比较。时间复杂度O(n),空间复杂度O(n)
  • 指针法:找到中点,反转中点之后的链表,再比较。时间复杂度O(n),空间复杂度O(1)

通过代码如下:

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
from math import * class Solution:
# # 改为数组:时间复杂度O(n),空间复杂度O(n)
# def isPalindrome(self, head: ListNode) -> bool:
# l = []
# while head:
# l.append(head.val)
# head = head.next
# return l == l[::-1] # 指针法:时间复杂度O(n),空间复杂度O(1)。找到中点,反转中点之后的链表,再比较
def isPalindrome(self, head: ListNode) -> bool:
if not head or not head.next:
return True
# 找到中点,快指针走的路程是慢的两倍,快指针结束慢指针刚好在中间
f = s = head
while f:
s = s.next
f = f.next.next if f.next else f.next # 反转中点之后的链表,1->2->0->2->1 ————》 1->2->0<-2<-1
c, p = s, None
while c:
n = c.next
c.next = p
p = c
c = n # 相对比较
while p:
if head.val != p.val:
return False
head = head.next
p = p.next
return True

最新文章

  1. HDU 1394 Minimum Inversion Number(最小逆序数 线段树)
  2. OpenGL的学习与认识
  3. 【WPF】布局控件总结
  4. navicat重新系统丢失libmysql_e
  5. AutoCAD 2012安装错误,与.net framework (1603错误)以及ms2005vc++的问题。
  6. WebLogic 安装
  7. css div旋转之后自适应
  8. Linux 性能搜集【top/vmstat/iostat】
  9. java的断言(assert)
  10. 初识STM32中的USMART组件
  11. JavaScript-DOM(2)
  12. [20180423]flashback tablespace与snapshot standby.txt
  13. JDBC的DBUtils源码
  14. Java8中list转map
  15. Eclipse------用Tomcat运行项目后出现:严重: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener
  16. Fiddler 断点调试http请求
  17. AngularJS 解决 SEO 问题
  18. ArcGIS软件操作——地图配准
  19. Linux性能监测:磁盘IO篇
  20. MySQL☞where与like

热门文章

  1. Luogu P1092 虫食算(枚举+剪枝)
  2. 洛谷P3300 城市规划
  3. I Hate It HDU - 1754 (线段树)
  4. Eclipse-搭建springboot项目报错
  5. Ubuntu18.04 修改IP地址、查看网关、防火墙
  6. PHP快速导出Excel文件 (采用xlsx Writer)
  7. tomcat9下载与安装
  8. 洛谷3128 [USACO15DEC]最大流Max Flow——树上差分
  9. HR招聘_(三)_招聘方法论(招聘途径及流程)
  10. 第十章—DOM(一)——Document类型