1.Question
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?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(!head || !head->next) return true;
ListNode *one_stride = head, *two_stride = head;
while(two_stride->next && two_stride->next->next)
{
one_stride = one_stride->next;
two_stride = two_stride->next->next;
}
ListNode* tail = reverseList(one_stride);
while(head)
{
if(head->val != tail->val) return false;
else
{
head = head->next;
tail = tail->next;
}
}
return true;
}
ListNode* reverseList(ListNode* head) {
if(head == NULL|| head->next == NULL) return head;
ListNode *pointFr = head, *pointMid = head->next, *pointLater = head->next->next;
pointMid->next = pointFr;
while(pointLater)
{
pointFr = pointMid;
pointMid = pointLater;
pointLater = pointLater->next;
pointMid->next = pointFr;
}
head->next = NULL;
return pointMid;
}
};
3.Note
a. 很无语的一道题目。莫名奇妙差一点时间就TLE,但在本地VS上能跑。
b. 思路很简单,找出中间节点,然后将后半段倒转,再从两段开始判断是否一一对称。其中找中间节点用快慢指针法。倒转还有一种思路,用一个last表示倒转的末端,head表示前端,还要一个temp表示last的下一位,并看temp是否有值,当temp为NULL是结束倒转。