234 Palindrome Linked List


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/*
//Time Limit Exceeded 
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if(head == NULL || head->next == NULL) return true;        
        vector<ListNode*> v;
        while(head){
            v.push_back(head);
            head=head->next;
        }
        for(int i= 0,j=v.size()-1; i<j;){
            if(v[i]->val != v[j]->val) return false;
        }
        return true;
    }
};
*/
// 1. revsercie sencond part
// 2. compare the first part == secondpart
// 3. how to get the middle position, slow and fast
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->next->next !=NULL){
            slow = slow->next;
            fast = fast->next->next;
        }
        
        ListNode* temp = reverseList(slow->next);
        slow->next = temp;
        slow = slow->next;
        
        temp = head;
        while(slow){
            if(slow->val != temp->val) return false;
            slow = slow->next;
            temp = temp->next;
        }
        return true;
    }
private:
    ListNode* reverseList(ListNode* head)
    {
        ListNode* pre = NULL;
        ListNode* temp = NULL;
        while(head){
            temp = head->next;
            head->next = pre;
            pre = head;
            head = temp;
        }
        return pre;
    }
};

相关文章:

  • 2020-04-13
  • 2020-06-07
  • 2021-11-15
  • 2019-12-23
  • 2021-03-13
  • 2021-12-21
  • 2020-04-11
  • 2018-03-29
猜你喜欢
  • 2018-03-21
  • 2021-11-23
  • 2020-02-14
  • 2019-09-17
  • 2021-12-10
  • 2019-09-07
  • 2020-02-14
相关资源
相似解决方案