Sharing my 24ms C++ solution


  • 0
    T
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
     
    class Solution {
    private:
        ListNode* reverseList(ListNode* head)
        {
            if(head==NULL || head->next==NULL)
                return head;
            ListNode* nextHead = head->next;
            head->next = NULL;
            ListNode* newHead=head;
            while(true)
            {
                ListNode* tmp = nextHead->next;
                nextHead->next = newHead;
                newHead = nextHead;
                nextHead = tmp;
                if(nextHead==NULL)
                    return newHead;
            }
        }
        
    public:
        bool isPalindrome(ListNode* head) {
            if(head==NULL || head->next==NULL)
                return true;
            
            ListNode* slow = head;
            ListNode* fast = head;
            while(fast && fast->next)
            {
                slow = slow->next;
                fast = fast->next->next;
            }
            
            if(fast==NULL)
                slow = reverseList(slow);
            else
            {
                slow->next = reverseList(slow->next);
                slow = slow->next;
            }
            
            ListNode* Head = head;
            while(slow)
            {
                if(slow->val!=Head->val)
                    return false;
                else
                {
                    slow = slow->next;
                    Head = Head->next;
                }
            }
            
            return true;
        }
    };

Log in to reply
 

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