Given the head of a singly linked list, return true if it is a palindrome or false otherwise.
Example 1:
Input: head = [1,2,2,1]
Output: true
Example 2:
Input: head = [1,2]
Output: false
Constraints:
- The number of nodes in the list is in the range [1, 105].
- 0 <= Node.val <= 9
Follow up: Could you do it in O(n) time and O(1) space?
# 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:
alist=[]
curr=head
while curr:
alist.append(curr.val)
curr=curr.next
lp, rp=0, len(alist)-1
while lp<rp:
if alist[lp]!=alist[rp]:
return False
else:
lp+=1
rp-=1
return True
'알고리즘 문제 > Leetcode' 카테고리의 다른 글
268. Missing Number (0) | 2023.01.12 |
---|---|
259. 3Sum Smaller (0) | 2023.01.12 |
61. Rotate List (0) | 2023.01.11 |
80. Remove Duplicates from Sorted Array II (0) | 2023.01.11 |
718. Maximum Length of Repeated Subarray (0) | 2023.01.11 |