题目描述
Given a singly linked list, determine if it is a palindrome.
Example 1:
1 | Input: 1->2 |
Example 2:
1 | Input: 1->2->2->1 |
Follow up:
Could you do it in O(n) time and O(1) space?
O(1)的空间复杂度,言外之意就是不借用数组等工具来做,那么最先想到的还是快慢指针。使用快指针来探索是否链表遍历到了头,慢指针来确定链表的中间位置。由于还要进行比较,所以在慢指针进行遍历的时候,需要把链表反转,方便之后的比较工作。
代码实现
1 | class Solution { |