2.6 Palindrome

1. Reverse and Compare:

    ListNode* reverseList(ListNode* head){
        if(!head) return head;
        ListNode* pre = NULL;
        while (head) {
            ListNode* tmp = head->next;
            head->next = pre;
            pre = head;
            head = tmp;
        }
        return pre;
    }
    bool isPalindrome(ListNode* head){
        if(!head || !head->next) return true;
        ListNode* fast = head;
        ListNode* slow = head;
        while (fast->next && fast->next->next) {
            fast = fast->next->next;
            slow = slow->next;
        }
        slow->next = reverseList(slow->next);
        slow = slow->next;
        while (slow){
            if(head->val != slow->val) return false;
            slow = slow->next;
            head = head->next;
        }
        return true;
    }

2. Using extra space ( stack)

    bool isPalindrome(ListNode* head){
        stack<int> stk;
        if(!head || !head->next) return true;
        ListNode* fast = head;
        ListNode* slow = head;
        while(fast && fast->next){
            stk.push(slow->val);
            fast = fast->next->next;
            slow = slow->next;
        }
        if(fast) slow = slow->next;//if the list has odd length we skip middle point;
        while(slow || !stk.empty()){
            if(slow->val != stk.top()) return false;
            slow = slow->next;
            stk.pop();
        }
        return true;
    }

你可能感兴趣的:(LinkedList)