234_Palindrome Linked List
Question
Given a singly linked list, determine if it is a palindrome.
Example:
linked list1 → 2 → 1 → Ø is a palindrome.
linked list1 → 2 → 3 → Ø is not a palindrome.
Follow up: Could you do it in O(n) time and O(1) space?
Solution 1
Convert the linked list to array, check if the array is a palindrome.
Time: extra space:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head:
return True
# convert linked list to array
ret = []
node = head
while node:
ret.append(node.val)
node = node.next
return ret == ret[::-1]Solution 2
Get the middle of the linked list using a slow pointer and a fast pointer
Reverse the second half of the linked list
Check if the first half and second half are identical
Time: Extra space:
Last updated