Why the result of my code is Time Limit Exceeded?Please help!


  • 0
    /**
    
    • 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(NULL==head || NULL==head->next)
      return true;
      ListNode *p=head, *q, *tmp;
      int size=0, i;
      while(NULL!=p){
      size++;
      p = p->next;
      }

       p = head;
       for(i=0; i<(size+1)/2; i++)
           p = p->next;
       q = p->next;
       
       while(NULL!=q){
           tmp = q;
           q = q->next;
           tmp->next = p;
           p = tmp;
       }
       
       q = head;
       
       for(i=0; i<(size/2); i++){
           if(q->val != p->val){
               return false;
           }
           q = q->next;
           p = p->next;
       }
       return true;
      

      }
      };


Log in to reply
 

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