mycode   89.42%

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
total = 0
p1 = p2 = head
while p1:
total += 1
p1 = p1.next
if total < 2:
return True
half = total // 2 - 1
while half :
p2 = p2.next
half -= 1
if total % 2 == 1:
part_2 = p2.next.next
else:
part_2 = p2.next
p2.next , last = None , None while part_2:
new_head = part_2.next
part_2.next = last
last = part_2
part_2 = new_head while head:
if not last or head.val != last.val:
return False
head , last= head.next , last.next
return True

参考

1、使用快慢指针,凡是用了额外空间

class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if not head or not head.next:
return True new_list = [] # 快慢指针法找链表的中点
slow = fast = head
while fast and fast.next:
new_list.insert(0, slow.val)
slow = slow.next
fast = fast.next.next if fast: # 链表有奇数个节点
slow = slow.next for val in new_list:
if val != slow.val:
return False
slow = slow.next
return True

2、使用快慢指针找重点,其他思路和我相同

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head or not head.next:
return True # 快慢指针法找链表的中点
slow = fast = head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next slow = slow.next # slow指向链表的后半段
slow = self.reverseList(slow) while slow:
if head.val != slow.val:
return False
slow = slow.next
head = head.next
return True def reverseList(self, head):
new_head = None
while head:
p = head
head = head.next
p.next = new_head
new_head = p
return new_head

最新文章

  1. [css3]跑马灯
  2. Html标签第一课
  3. 【部分原创】标准C语言的优先级、结合性、求值顺序、未定义行为和非确定行为浅析
  4. Github排行榜
  5. javascript的window.onload()方法和jQuery的$(document).ready()的对比
  6. Git for Windows
  7. Constructing Roads--hdu1102
  8. 菜鸟学习spring IOC有感
  9. 微信小程序开发之http到https的转化
  10. 【bzoj4009 hnoi2015】接水果
  11. GCD API记录(二)
  12. SqlServer 更改数据库名称
  13. (string 高精度) Lovekey hdu 2100
  14. 用深度学习LSTM炒股:对冲基金案例分析
  15. MySQL(慢日志记录)
  16. Eclipse 之使用技巧积累(一)
  17. Web api 访问HttpContext
  18. Rest分享
  19. LeetCode31.下一个排列 JavaScript
  20. centos 7 配置nginx 的yum源

热门文章

  1. jquery 滚动事件-记录自己常用的
  2. 2019.9.27PHP基础
  3. golang 方法
  4. 关于STM32中printf函数的重定向问题
  5. 修改linux系统TCP连接数
  6. DP问题练习2:网格路径数量计算问题
  7. Python中的字典和集合
  8. Tableau Sheet
  9. java 集合数组排序
  10. MyEclipse使用教程:导航代码(一)