-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path234.py
More file actions
59 lines (46 loc) · 1.16 KB
/
234.py
File metadata and controls
59 lines (46 loc) · 1.16 KB
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
50
51
52
53
54
55
56
57
58
59
'''
234. Palindrome Linked List
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
'''
# 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
ptr = self.reverseList(head)
count = 0
while head.next:
count += 1
while count > (0.5 * count):
if ptr.val != head.val:
return False
ptr = ptr.next
head = head.next
return True
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if None == head:
return
if None == head.next:
return head
current = head
pre = None
while current:
temp = current.next
current.next = pre
pre = current
current = temp
return pre