-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path234.py
50 lines (45 loc) · 1.28 KB
/
234.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 用list存储链表中的值,再进行回文判断
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
res = []
while head != None:
res.append(head.val)
head = head.next
for i in range(len(res)//2):
if res[i] != res[len(res)-i-1]:
return False
return True
def isPalindrome1(self, head):
if head == None or head.next == None:
return True
slow = head
fast = head
while fast.next != None and fast.next.next != None:
slow = slow.next
fast = fast.next.next
def reverselist(head):
pre = None
cur = head
while cur != None:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
return pre
slow.next = reverselist(slow.next)
slow = slow.next
while slow != None:
if slow.val != head.val:
return False
slow = slow.next
head = head.next
return True