时间复杂度分析:需要遍历整个链表,时间复杂度为 O(n),空间复杂度为 O(1)。

代码如下:

bool isPalindrome(ListNode* head) {
    if (head == nullptr || head->next == nullptr) {
        return true;
    }
    ListNode* slow = head;
    ListNode* fast = head;
    while (fast->next != nullptr && fast->next->next != nullptr) {
        slow = slow->next;
        fast = fast->next->next;
    }
    ListNode* secondHalfHead = reverseList(slow->next);
    ListNode* p1 = head;
    ListNode* p2 = secondHalfHead;
    bool result = true;
    while (p2 != nullptr) {
        if (p1->val != p2->val) {
            result = false;
            break;
        }
        p1 = p1->next;
        p2 = p2->next;
    }
    slow->next = reverseList(secondHalfHead);
    return result;
}

ListNode* reverseList(ListNode* head) {
    ListNode* newHead = nullptr;
    while (head != nullptr) {
        ListNode* nextNode = head->next;
        head->next = newHead;
        newHead = head;
        head = nextNode;
    }
    return newHead;
}
c++全部代码:请编写算法判断链表是否为回文链表。如果是返回 true ;否则返回 false。要求:空间复杂度为O1并请分析程序的时间性能。

原文地址: https://www.cveoy.top/t/topic/bbLL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录