-
Notifications
You must be signed in to change notification settings - Fork 0
/
234.py
63 lines (59 loc) · 1.7 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# 234. Palindrome Linked List
# Given the head of a singly linked list, return true if it is a palindrome or false otherwise.
# 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 reverseLinkedList(self,head):
# returns pointer to reversed linked list with last node having "None" as next
prev = None
cur = head
while cur != None:
next = cur.next
cur.next = prev
prev = cur
cur = next
return prev
def returnEvenLengthList(self,head,length):
i = 0
mid = length / 2
cur = head
prev = head
while i<mid:
prev = cur
cur = cur.next
i+=1
prev.next = cur.next
return head
def getLength(self,head):
cur = head
i = 0
while cur != None:
cur = cur.next
i+=1
return i
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
length = self.getLength(head)
mid = length / 2
if length == 1: return True
if length % 2 != 0:
head = self.returnEvenLengthList(head,length)
length-=1
i=0
cur = head
while i<mid:
cur = cur.next
i+=1
rightHalf = self.reverseLinkedList(cur)
leftHalf = head
while rightHalf != None:
if leftHalf.val != rightHalf.val: return False
leftHalf = leftHalf.next
rightHalf = rightHalf.next
return True