LeetCode题解之链表(二)

130 阅读1分钟

234. 回文链表

class Solution {
public:
/*
方法一:用数组存储再用首尾指针判断:时间o(n)空间o(n)
方法二:由于只需要o(1)空间,所以是两个指针同时移动和比较,需要翻转后一半的链表:用快慢指针找到中间的点,翻转中间点以后的点
*/
    bool isPalindrome(ListNode* head) {
        if(!head || !head->next) return true;
        //利用快慢指针找到中间的节点
        auto slow = head,fast = head;
        while(fast && fast->next)
        {
            slow = slow->next;
            fast = fast->next->next;
        }
        //开始翻转链表
        auto pre = slow;auto a = slow->next;
        while(a)
        {
            auto nex = a->next;
            a->next = pre;
            pre = a;
            a = nex;
        }
        slow->next = nullptr;
        //开始比较是否相等
        while(head && pre)
        {
            if(head->val == pre->val) 
            {
                head = head->next;
                pre = pre->next;
            }
            else return false;
        }
        return true;

    }
};