LeetCode OJ---234. Palindrome Linked List

来源:互联网 发布:程序员教程 第4版 pdf 编辑:程序博客网 时间:2024/06/07 08:55


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;
        
    }
};



0 0