Skip to content

Commit 9eae3c2

Browse files
committed
Palindrome Linked List
1 parent 380e58b commit 9eae3c2

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# 234. Palindrome Linked List
2+
# Topics: 'Stack', 'Recursion', 'Linked List', 'Two Pointers'
3+
# Given the head of a singly linked list, return true if it is a or false otherwise.
4+
5+
# Example 1:
6+
7+
# Input: head = [1,2,2,1]
8+
# Output: true
9+
10+
# Example 2:
11+
12+
# Input: head = [1,2]
13+
# Output: false
14+
15+
16+
17+
# Constraints:
18+
19+
# The number of nodes in the list is in the range [1, 105].
20+
# 0 <= Node.val <= 9
21+
22+
23+
# Follow up: Could you do it in O(n) time and O(1) space?
24+
25+
26+
from typing import Optional
27+
28+
class ListNode:
29+
def __init__(self, val=0, next=None):
30+
self.val = val
31+
self.next = next
32+
33+
# Memory O(n), Time O(n)
34+
class Solution:
35+
def isPalindrome(self, head: Optional[ListNode]) -> bool:
36+
arr = []
37+
cur = head
38+
while cur:
39+
arr.append(cur.val)
40+
cur = cur.next
41+
42+
L, R = 0, len(arr)-1
43+
while L < R:
44+
if arr[L] != arr[R]:
45+
return False
46+
L+=1
47+
R-=1
48+
return True

0 commit comments

Comments
 (0)