leetcode-easy-listnode-234 Palindrome Linked List
2024-09-05 14:23:29
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
最新文章
- [css3]跑马灯
- Html标签第一课
- 【部分原创】标准C语言的优先级、结合性、求值顺序、未定义行为和非确定行为浅析
- Github排行榜
- javascript的window.onload()方法和jQuery的$(document).ready()的对比
- Git for Windows
- Constructing Roads--hdu1102
- 菜鸟学习spring IOC有感
- 微信小程序开发之http到https的转化
- 【bzoj4009 hnoi2015】接水果
- GCD API记录(二)
- SqlServer 更改数据库名称
- (string 高精度) Lovekey hdu 2100
- 用深度学习LSTM炒股:对冲基金案例分析
- MySQL(慢日志记录)
- Eclipse 之使用技巧积累(一)
- Web api 访问HttpContext
- Rest分享
- LeetCode31.下一个排列 JavaScript
- centos 7 配置nginx 的yum源