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?
Subscribe to see which companies asked this question
/**
* 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==NULL || head->next==NULL)
return true;
ListNode *fast = head;
ListNode *slow = head;
stack<int> s;
s.push(head->val);
while(fast->next && fast->next->next)
{
fast = fast->next->next;
slow = slow->next;
s.push(slow->val);
}
if(!fast->next)
s.pop();
while(slow->next)
{
slow = slow->next;
int tmp = s.top();
s.pop();
if(tmp != slow->val)
return false;
}
return true;
}
};