原题:
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2 Output: falseExample 2:
Input: 1->2->2->1 Output: trueFollow up:
Could you do it in O(n) time and O(1) space?
一开始想不到满足条件的算法,参考了一下网上的,结合了一下各种办法不过要改变原结构,步骤是:
1 设置快慢指针得到中点
2 从中点开始向后逆置指针(需要三个指针进行操作)
3 从两边向中间遍历
结果:
Success
Runtime: 20 ms, faster than 96.14% of C++ online submissions for Palindrome Linked List.
Memory Usage: 12.6 MB, less than 71.95% of C++ online submissions for Palindrome Linked List.
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int