Using Stack to solve the problem


  • -2
    F
    /**
     * 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) return true;
            stack<int> box;
            ListNode* node = head;
            int count=0;
            while(node)
            {
                count++;
                node = node->next;
            }
            node = head;
            for(int i=0; i<count/2; i++) 
            {
                box.push(node->val);
                node = node->next;
            }
            if(count%2!=0) node= node->next;
            while(node)
            {
                if(node->val==box.top())
                {
                    box.pop();
                    node = node->next;
                }
                else
                {
                    return false;
                }
            }
            return box.empty();
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.