234. Palindrome Linked List

2016-09-29  本文已影响0人  a_void

Given a singly linked list, determine if it is a palindrome.

Solution1: no change to original list

/**
 * 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) return true;
        vector<int> v;
        for(ListNode*p = head;p!=NULL;p=p->next) v.push_back(p->val);
        for(int i=0,j=v.size()-1;i < j;i++, j--){
            if(v[i] != v[j]) return false;
        }
        return true;
    }
};

Solution2: space=o(1)

/**
 * 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* fast = head, *slow = head;
        while(fast && fast->next){
            slow = slow->next;
            fast = fast->next->next;
        }
        for(ListNode*p1 = head, *p2=reverse(slow);p1 != slow; p1=p1->next, p2=p2->next){
            if(p1->val != p2->val) return false;
        }
        return true;
    }
    ListNode* reverse(ListNode* head){
        if(NULL == head || NULL == head->next) return head;
        ListNode *p1 = head, *p2 = head->next;
        p1->next = NULL;
        while(NULL != p2){
            ListNode* t = p2->next;
            p2->next = p1;
            p1 = p2;
            p2 = t;
        }
        return p1;
    }
};
上一篇下一篇

猜你喜欢

热点阅读