您的位置:首页 > 编程语言 > Python开发

【LeetCode】Python实现-234. 回文链表

2019-03-10 21:42 399 查看

请判断一个链表是否为回文链表。
示例1:

输入: 1->2
输出: false

示例2:

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

别人的解答:
设置快慢指针,当快指针走完时,慢指针刚好走到中点,随即原地将后半段反转,然后进行回文判断。该解法:空间复杂度O(1)

# 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 head is None or head.next is None:
return True
if head.next.next is None:
return head.val == head.next.val
fast = slow = q = head
while fast.next and fast.next.next:   #这里快指针的判读条件跟判断环形有一点不同
fast = fast.next.next
slow = slow.next
def reverse_list(head):
if head is None:
return head
cur = head
pre = None
nxt = cur.next
while nxt:
cur.next = pre
pre = cur
cur = nxt
nxt = nxt.next
cur.next = pre
return cur
p = reverse_list(slow.next)
while p.next:
if p.val != q.val:
return False
p = p.next
q = q.next
return p.val == q.val
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: