leetcode_234

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?

Solutions

  1. two pointers

  2. Fast pointer and slow pointer moves 2 an 1 nodes in each step.

  3. When the fast pointer moves to the end, the first half of the link list is reversed and the slower pointer is right at the middle(if the length is odd) of the link list.

  4. Check if the linked list is a palindrome by moving two linked lists simultaneously.

  1. two pass

  • Loop through the linked list to count the length.

  • Then reverse the first half of the link list and the following steps are the same as steps in the first method.

Last updated

Was this helpful?