My accept c++ code


  • 4
    P
    class Solution {
    public:
        bool isPalindrome(ListNode* head) {
            int len = 0;
            ListNode* p  = head;
            while(p)
            {
                ++len;
                p = p->next;
            }
            
            p = head;
            ListNode* p1 = nullptr,*tmp;
            for(int i = 0;i < len/2;++i)
            {
                tmp = p->next;
                p->next = p1;
                p1 = p;
                p = tmp;
            }
            if(len % 2)
                p = p->next;
            for(int i = 0;i <len/2;++i)
            {
                if(p1->val != p->val)
                    return false;
                p1 = p1->next;
                p = p->next;
            }
            return true;
            
        }
    };

  • 0
    S

    Nice solution, although it would be more readable if you renamed e.g. tmp as next and p1 as prev etc.


Log in to reply
 

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