Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
Example 2:
Input: 1->2->2->1
Output: true
Follow up:
Could you do it in O(n) time and O(1) space?
Solution in python:
# 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: ListNode) -> bool:
alist = []
while head != None:
alist.append(head.val)
head = head.next
if len(alist) <= 1:
return True
i = 0
j = len(alist)-1
while i < j:
if j - i < 1:
return True
elif alist[i] == alist[j]:
i += 1
j -= 1
else:
return False
return True
留言