跳转至

234.回文链表 (Easy)*

题目描述*

请判断一个链表是否为回文链表。

示例*

输入: 1->2

输出: false

输入: 1->2->2->1

输出: true

进阶*

你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

代码*

快慢指针,fast 是 slow 的两倍,找到中间结点,然后把后半段链表反转(如果反转前半段链表还需要考虑奇偶的问题),比较前后两链表。如果没有空间限制还可以用栈。

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if(head == nullptr || head->next == nullptr) {
            return true;
        }
        ListNode *slow = head, *fast = head;
        // 这样的条件就不用判断奇偶
        while(fast->next != nullptr && fast->next->next != nullptr) {
            slow = slow->next;
            fast = fast->next->next;
        }
        ListNode *last = slow->next, *pre = head;
        // 后半段链表反转
        slow = nullptr, fast = last;
        while(fast != nullptr) {
            ListNode *p = fast->next;
            fast->next = slow;
            slow = fast;
            fast = p;
        }
        // 反转后 slow 成为后半段链表头
        while(slow != nullptr) {
            if(slow->val != pre->val) {
                return false;
            }
            slow = slow->next;
            pre = pre->next;
        }
        return true;
    }
};

最后更新: July 23, 2022