力扣 面试题 02.06. 回文链表 链表 模拟

https://leetcode-cn.com/problems/palindrome-linked-list-lcci/
力扣 面试题 02.06. 回文链表 链表 模拟_第1张图片

思路:如果是 O ( n ) O(n) O(n)的空间复杂度,那么很好写,存到数组中判断即可。我们考虑怎么做到 O ( 1 ) O(1) O(1)的空间复杂度。可以利用快慢指针得到链表的中点,然后把前半部分翻转,再与后半部分逐一比较即可。更进一步,我们可以把移动慢指针的过程与翻转的过程结合在一起。注意当链表个数为奇数时,最中间的那个节点是不需要考虑的。

/**
 * 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)
            return 1;
        ListNode *fast=head,*slow=head,*myhead=nullptr;
        int n=0;
        while(fast){
            ++n;
            fast=fast->next;
            if(fast){
                ++n;
                fast=fast->next;
                //移动slow指针 同时进行翻转操作
                ListNode *tmp=slow->next;
                slow->next=myhead;
                myhead=slow;
                slow=tmp;
            }
        }
        if(n&1)
            slow=slow->next;
        while(slow&&slow->val==myhead->val)
            slow=slow->next,myhead=myhead->next;
        return slow==myhead;
    }
};

你可能感兴趣的:(面试题,模拟,链表)