如何判断一个链表是回文链表。(第一个我写的,下面我根据其他人改编的)
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def isPalindrome1(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head:
return True
temp_list = []
temp = head
temp_list.append(temp.val)
while temp.next:
temp = temp.next
temp_list.append(temp.val)
return temp_list == temp_list[::-1]
def isPalindrome2(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head is None:
return True
# 这一部分代码很经典,通过fast和slow之间的差值计算出了什么地方时中点
fast = head
slow = head
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
# 这一个部分代码是链表反转
cur = slow.next
slow.next = None
pre = None
while cur:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
# 这一部分才是最后的比较部分
while pre:
if pre.val != head.val:
return False
pre = pre.next
head = head.next
return True
def isPalindrome(self, head):
"""这是个神奇的东西,我没明白
:type head: ListNode
:rtype: bool
"""
s1 = 0
s2 = 0
t = 1
while head:
s1 = s1 * 10 + head.val
s2 = s2 + t * head.val
t = t * 10
head = head.next
return s1 == s2
if __name__ == '__main__':
s1 = Solution()
root = ListNode(1)
n1 = ListNode(2)
n2 = ListNode(2)
n3 = ListNode(1)
n2.next = n3
n1.next = n2
root.next = n1
print(s1.isPalindrome(root))