题目
思路
- 先依次遍历原链表,将每个结点的值存放在列表s
- 接着反转链表,遍历反转后的列表,将每个结点的值存放至列表t
- 两个列表相等,即回文 (一定要先遍历原链表获取列表s,再进行反转 )
代码
# 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 isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
s =[]
p =head
while p:
s.append(p.val)
p=p.next
#反转
pre = None
cur = head
while cur:
next=cur.next
cur.next=pre
pre = cur
cur=next
t = []
while pre:
t.append(pre.val)
pre = pre.next
if s==t:
return True
else:
return False
ps:
先反转,再去p = head 获取的不是原head