# 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
# 1. Get the midpoint (slow)
slow = fast = cur = head
while fast and fast.next:
fast, slow = fast.next.next, slow.next
# 2. Push the second half into the stack
stack = [slow.val]
while slow.next:
slow = slow.next
stack.append(slow.val)
# 3. Comparison
while stack:
if stack.pop() != cur.val:
return False
cur = cur.next
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
"""
fast = slow = head
# find the mid node
# 一般走两步的都会是两个判断条件
while fast and fast.next:
fast = fast.next.next
slow = slow.next
pre = None
while slow:
nxt = slow.next
slow.next = pre
pre= slow
slow = nxt
# compare the first and second half nodes
while pre: # while node and head:
if pre.val != head.val:
return False
pre = pre.next
head = head.next
return True
二刷:
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 not head or not head.next:
return True
slow = head
fast = head.next
stack = [head.val]
while fast and fast.next:
slow = slow.next
fast = fast.next.next
stack.append(slow.val)
# 通过while lopp后,fast是不是none来判断linkedlist个数是奇数还是偶数,如果是奇数,mid停留在正中间,stack=[1,2,3]后半部分为2,1,需要先pop出3,再进行比较
if not fast:
stack.pop()
while slow.next:
slow = slow.next
node = stack.pop()
if slow.val != node:
return False
return True
2。
注意fast和slow的初始条件都是head, 并且while终止条件是fast and fast.next。这样循环结束时slow停留在中间靠后的位置(偶数个node)。便于我们再反转的时候起始值准确的对应后半部分