Palindrome Linked List (leetcode 234)

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?

将前一半倒序(头插,然后对比)

/** * 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) {

        int l = len(head);
        if (l < 2) {
            return true;
        }
        ListNode* n = NULL;
        ListNode* t;
        int i = l / 2;
        for(int j = 0; j < i; ++j) {
            t = head;
            head = head->next;
            t->next = n;
            n = t;
        }
        if (l % 2 != 0) {
            head = head->next;
        }
        while(t != NULL && t->val == head->val) {
            t=t->next;
            head=head->next;
        }
        if (t == NULL) {
            return true;
        }
        return false;
    }
    // 可以不获取list长度,用快慢指针获取中间位置。复杂度没有降低
    int len(ListNode* head) {
        ListNode* t = head;
        int i = 0;
        while(t != NULL) {
            ++i;
            t = t->next;
        }
        return i;
    }
};

你可能感兴趣的:(Palindrome Linked List (leetcode 234))