[LeetCode] 234. Palindrome Linked List

来源:互联网 发布:临沂php培训 编辑:程序博客网 时间:2024/06/08 14:31

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?

class Solution {public:    bool isPalindrome(ListNode* head) {        ListNode *FstHalf = head;        ListNode *SndHalf = HalfHead(head);        SndHalf = Reverse(SndHalf);        while (FstHalf && SndHalf) {            if (FstHalf->val != SndHalf->val)                return false;            FstHalf = FstHalf->next;            SndHalf = SndHalf->next;        }        return true;    }private:    ListNode *HalfHead(ListNode *head) {        ListNode *slow, *fast;        slow = fast = head;        while (fast && fast->next) {            slow = slow->next;            fast = fast->next->next;        }        return fast ? slow->next : slow;    }    ListNode *Reverse(ListNode *head) {        if (head == nullptr || head->next == nullptr)            return head;        ListNode *revhead = Reverse(head->next);        head->next->next = head;        head->next = nullptr;        return revhead;    }    /*    ListNode *Reverse(ListNode *head) {        ListNode *prev = nullptr, *cur;        while (head) {            cur = head;            head = head->next;            cur->next = prev;            prev = cur;        }        return prev;    }    */};

这里写图片描述
这里写图片描述

原创粉丝点击