Press "Enter" to skip to content

花花酱 LeetCode 234. Palindrome Linked List

题目大意:检查一个单向链表是不是回文。

Problem:

https://leetcode.com/problems/palindrome-linked-list/description/

Given a singly linked list, determine if it is a palindrome.

Follow up:
Could you do it in O(n) time and O(1) space?

Idea:

  1. use fast / slow pointers to find the middle node and see whether the list has odd/even number of elements.
  2. Reverse the right half the list, and compare with the left half

E.g.
1->2->3->4->3->2->1->null
fast = null
slow = 4
slow->next = 3
reverse(slow->next)
null<-3<-2<-1 compare with 1->2->3->…

Solution: 1

Time complexity: O(n)

Space complexity: O(1)

C++

 

 

 

请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.

Buy anything from Amazon to support our website
您可以通过在亚马逊上购物(任意商品)来支持我们

Paypal
Venmo
huahualeetcode
微信打赏

3 Comments

  1. longspring longspring May 2, 2018

    这题是不是先将fast 初始的时候让他等于 head->next,这样就不需要检查odd or even了。一快一慢前进的时候,slow指到的就会是要reverse的head。

    • longspring longspring May 2, 2018

      如果是这样的话一开始就需要检查 head->next是不是nullptr
      if (!head || !head->next) return true;

      • longspring longspring May 2, 2018

        第一段comment有个typo,应该说这样slow->next就会always是指到要reverse的head。

Leave a Reply