-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPalindrome Linked List.py
More file actions
41 lines (40 loc) · 1.08 KB
/
Palindrome Linked List.py
File metadata and controls
41 lines (40 loc) · 1.08 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
# 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:
def reverse(head):
if not head or not head.next:
return head
prev,cur,nex=head,head.next,head.next.next
while nex:
cur.next=prev
prev=cur
cur=nex
nex=nex.next
cur.next=prev
head.next=None
return cur
if not head.next:
return True
count=0
temp=head
while temp:
count+=1
temp=temp.next
count=count//2
temp=head
while count>1:
count-=1
temp=temp.next
head2=reverse(temp.next)
temp.next=None
head1=head
while head1:
if head1.val != head2.val:
return False
head1=head1.next
head2=head2.next
return True