面试题 02.06

Implement a function to check if a linked list is a palindrome.

Example 1:

Input: 1->2 Output: false Example 2:

Input: 1->2->2->1 Output: true

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

Solutions

  • the same as problem 234

  • revese the first half two times

/**
 * 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 || !head->next) return true;
        ListNode * prev = nullptr, * right = head;
        while (right && right->next) {
            right = right->next->next;
            ListNode * next = head->next;
            head->next = prev;
            prev = head;
            head = next;
        }

        ListNode * l = prev, * r = head;
        if (right) r = r->next
        prev = head;
        bool is_paline = true;
        while (l) {
            if (l->val != r->val)
                is_paline = false;
            ListNode * lnext = l->next;
            l->next = prev;
            prev = l;

            l = lnext; r = r->next;
        }
        return is_paline;
    }
};

Last updated

Was this helpful?