1 Star 0 Fork 0

wd6/LeetCode-1

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
palindrome-linked-list.py 1.13 KB
一键复制 编辑 原始数据 按行查看 历史
# Time: O(n)
# Space: O(1)
#
# Given a singly linked list, determine if it is a palindrome.
#
# Follow up:
# Could you do it in O(n) time and O(1) space?
#
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
class Solution:
# @param {ListNode} head
# @return {boolean}
def isPalindrome(self, head):
reverse, fast = None, head
# Reverse the first half part of the list.
while fast and fast.next:
fast = fast.next.next
head.next, reverse, head = reverse, head, head.next
# If the number of the nodes is odd,
# set the head of the tail list to the next of the median node.
tail = head.next if fast else head
# Compare the reversed first half list with the second half list.
# And restore the reversed first half list.
is_palindrome = True
while reverse:
is_palindrome = is_palindrome and reverse.val == tail.val
reverse.next, head, reverse = head, reverse, reverse.next
tail = tail.next
return is_palindrome
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/wd6/LeetCode-1.git
git@gitee.com:wd6/LeetCode-1.git
wd6
LeetCode-1
LeetCode-1
master

搜索帮助