Palindrome Linked List

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?

Analysis

由于单链表没有反向指针,因此就需要将链表分为左右两部分进行比较。找中点可以用快满指针,找到之后翻转右边一半的链表,这时就可以进行一对一比较了。

参考: https://leetcode.com/problems/palindrome-linked-list/discuss/64501/Java-easy-to-understand

In the beginning, set two pointersfastandslowstarting at the head.

1 -> 1 -> 2 -> 1 -> null 
sf

(1) Move:fastpointer goes to the end, andslowgoes to the middle.

1 -> 1 -> 2 -> 1 -> null 
          s          f

(2) Reverse: the right half is reversed, andslowpointer becomes the 2nd head.

(3) Compare: run the two pointersheadandslowtogether and compare.

Solution

Find Mid Point + Reverse + Compare --- O(n) time, O(1) space

Don't need to make the right half smaller: https://leetcode.com/problems/palindrome-linked-list/discuss/64501/Java-easy-to-understand/66206

Reference

https://leetcode.com/problems/palindrome-linked-list/discuss/64501/Java-easy-to-understand

Last updated

Was this helpful?