Skip to content

Commit c125b46

Browse files
committed
palindrome linked list
1 parent de80db5 commit c125b46

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

234.PalindromeLinkedList.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
"""
2+
234. Palindrome Linked List
3+
Easy
4+
Linked List | Two Pointers | Stack | Recursion
5+
---
6+
Given the head of a singly linked list, return true if it is a palindrome or false otherwise.
7+
8+
Example 1:
9+
Input: head = [1,2,2,1]
10+
Output: true
11+
12+
Example 2:
13+
Input: head = [1,2]
14+
Output: false
15+
16+
Constraints:
17+
The number of nodes in the list is in the range [1, 105].
18+
0 <= Node.val <= 9
19+
20+
Follow up: Could you do it in O(n) time and O(1) space?
21+
"""
22+
23+
from typing import Optional
24+
25+
# Definition for singly-linked list.
26+
class ListNode:
27+
def __init__(self, val=0, next=None):
28+
self.val = val
29+
self.next = next
30+
31+
32+
# O(n) time | O(1) space
33+
class Solution:
34+
def isPalindrome(self, head: Optional[ListNode]) -> bool:
35+
# find middle
36+
walker = runner = head
37+
while runner and runner.next:
38+
walker = walker.next
39+
runner = runner.next.next
40+
41+
# reverse second half
42+
rev = None
43+
curr = walker
44+
while curr != None:
45+
nextTemp = curr.next
46+
curr.next = rev
47+
rev = curr
48+
curr = nextTemp
49+
50+
# check two half
51+
while rev and rev.val == head.val:
52+
head = head.next
53+
rev = rev.next
54+
55+
return not rev

0 commit comments

Comments
 (0)