LeetCode 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?

/**
 * 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 len = 0;
        ListNode* node = head;
        while (node != NULL) {
            node = node->next;
            len++;
        }
        if (len < 2) {
            return true;
        }
        
        int step = len / 2;
        ListNode* prev = NULL;
        node = head;
        while (step-- > 0) {
            prev = node;
            node = node->next;
        }
        prev->next = NULL;
        
        ListNode* head1 = head;
        ListNode* head2 = reverse(node);
        while (head1 != NULL) {
            if (head1->val != head2->val) {
                return false;
            }
            head1 = head1->next;
            head2 = head2->next;
        }
        return true;
    }
    
    ListNode* reverse(ListNode* head) {
        ListNode* prev = NULL;
        ListNode* node = head;
        while (node != NULL) {
            ListNode* next = node->next;
            node->next = prev;
            prev = node;
            node = next;
        }
        return prev;
    }
};

一次过

posted @ 2015-07-11 19:49  卖程序的小歪  阅读(214)  评论(0编辑  收藏  举报