【LeetCode】234. Palindrome Linked List

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

Follow up:
Could you do it in O(n) time and O(1) space?

【思路一】将list反转到新list,后一一进行比较。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverse(ListNode* head)
    {
        ListNode* ptr = NULL;
        while(head)
        {
            ListNode* tmp = new ListNode(head->val);
            tmp->next = ptr;
            ptr = tmp;
            head = head->next;
        }
        return ptr;
    };
    bool isPalindrome(ListNode* head) {
        if(head == NULL) return true;
        ListNode* rev = reverse(head);
        while(head)
        {
            if(rev->val != head->val)
             return false;
            else
            {
                rev =rev->next;
                head = head->next;
            }
        }
        return true;
    }
};

【思路二】将链表元素装入Vector内,前后开始比较。

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


你可能感兴趣的:(【LeetCode】234. Palindrome Linked List)