-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.py
More file actions
39 lines (33 loc) · 936 Bytes
/
solution.py
File metadata and controls
39 lines (33 loc) · 936 Bytes
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
# 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
"""
length = 0
p = head
# get the length of linked list
while p:
length += 1
p = p.next
# reverse the half of the linked list
index = 0
p = None
while index < length / 2:
index += 1
p, head, p.next = head, head.next, p
if length % 2 == 1:
head = head.next
# compare the two linked list
while p and head:
if p.val != head.val:
return False
else:
p = p.next
head = head.next
return True