-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
palindromelinkedlist.py
43 lines (34 loc) · 966 Bytes
/
palindromelinkedlist.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
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: Optional[ListNode]) -> bool:
len=0
dummy=head
while dummy:
len +=1
dummy=dummy.next
mid=len // 2
i=0
def reverse(head):
prev=None
while head:
temp=head
head=head.next
temp.next=prev
prev=temp
return prev
first=second=head
while i< mid:
second=second.next
i +=1
seond=reverse(second)
while first and second:
if first.val != second.val:
return False
else:
first=first.next
second=second.next
return True