My c++ code with 28ms 2n maybe too slow.


  • 0
    H

    class Solution {
    public:
    bool isPalindrome(ListNode* head) {
    if(head == NULL || head->next == NULL) return true;
    ListNode *slow = head;
    ListNode *fast = head;
    ListNode *last = head;
    while(fast!=NULL && fast->next!=NULL){
    fast = fast->next->next;
    last = slow;
    slow = slow->next;
    }
    last->next =NULL;
    ListNode tail = NULL;
    if(fast == NULL){
    //odd 2 4
    tail = reverseList(slow);
    }
    else{
    //even 1 3 7
    tail = reverseList(slow->next);
    }
    while(head!=NULL && head->val == tail->val){
    head = head->next;
    tail = tail->next;
    }
    return (head == NULL)?true:false;
    }
    ListNode
    reverseList(ListNode *head){
    if(head == NULL || head->next == NULL) return head;
    ListNode *p = head->next;
    ListNode *next = p->next;
    ListNode *last = head;
    while(p!=NULL){
    next = p->next;
    p->next = last;
    if(last == head) last->next = NULL;
    last = p;
    p = next;
    }
    return last;

    }
    

    };


Log in to reply
 

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