先用stack把它装起来,计算count, 然后出栈, 后半部分和前半部分比较
# 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
stack = []
count = 0
p = head
while p:
stack.append(p)
p = p.next
count += 1
count = count / 2
while count:
if head.val != stack.pop().val:
return False
head = head.next
count -= 1
return True
一边找到中点一边把前面反转了,然后比较前半部分和后半部分
# 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
pre = None
while fast and fast.next:
fast = fast.next.next
curr = slow.next
slow.next = pre
pre = slow
slow = curr
if fast:
slow = slow.next
while pre and slow:
if pre.val != slow.val:
return False
pre = pre.next
slow = slow.next
return True