Accepted C++ solution


  • 0
    Q

    class Solution {
    public:
    bool isPalindrome(ListNode* head) {
    if(head==NULL||head->next==NULL)
    return true;
    ListNode* slow=head;
    ListNode* fast=head;
    while(fast->next!=NULL){
    fast=fast->next;
    if(fast->next!=NULL)
    fast=fast->next;
    slow=slow->next;
    }
    ListNode* reversehead=reverseList(slow);
    while(head!=NULL&&reversehead!=NULL){
    if(head->val!=reversehead->val){
    return false;
    }
    head=head->next;
    reversehead=reversehead->next;
    }
    return true;
    }
    ListNode* reverseList(ListNode* head){
    if(head==NULL||head->next==NULL)
    return head;
    ListNode* pre=NULL;
    ListNode* current=head;
    ListNode* post=NULL;
    while(current!=NULL){
    post=current->next;
    current->next=pre;
    pre=current;
    current=post;
    }
    return pre;
    }

    };


Log in to reply
 

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