跳转至

234 回文链表

https://leetcode.cn/problems/palindrome-linked-list/solutions/457059/hui-wen-lian-biao-by-leetcode-solution/?envType=study-plan-v2&envId=top-100-liked

递归版

利用函数递归特性,当函数遍历到最底层遇到终止条件才会返回,终止条件设置为nullptr,则函数到达最后一个节点才会返回

此时我们设置firstPointer指向第一个节点,当函数开始返回时,将curNode与firstPointer的值进行比较

如果某次比较发现不相等,那么说明不是回文链表,需要向上传递结果,因此返回值设置为bool类型

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
private:
    ListNode* firstPointer;
public:
    bool recursivelyCheck(ListNode* curNode){
        if(!curNode)
            return true;
        if(!recursivelyCheck(curNode->next))
            return false;
        if(firstPointer->val != curNode->val)
            return false;
        firstPointer = firstPointer->next;
        return true;
    }
    bool isPalindrome(ListNode* head) {
        firstPointer = head;
        return recursivelyCheck(head);
    }
};

复杂度分析

  • 时间复杂度:O(n),其中 n 指的是链表的大小。
  • 空间复杂度:O(n),其中 n 指的是链表的大小。

迭代版

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
private:
    ListNode* reverseList(ListNode* head) {
        ListNode* prev = nullptr;
        ListNode* cur = head;
        while (cur) {
            ListNode* next = cur->next;
            cur->next = prev;
            prev = cur;
            cur = next;
        }
        return prev;
    }
    ListNode* getFirstEnd(ListNode* head) {
        ListNode *fast = head, *slow = head;
        while (fast->next != nullptr && fast->next->next != nullptr) {
            fast = fast->next->next;
            slow = slow->next;
        }
        return slow;
    }

public:
    bool isPalindrome(ListNode* head) {
        if (!head)
            return true;
        ListNode* firstEnd = getFirstEnd(head);
        ListNode* secondHead = reverseList(firstEnd->next);
        ListNode *p1 = head, *p2 = secondHead;
        while (p2) {
            if (p1->val != p2->val)
                return false;
            p1 = p1->next;
            p2 = p2->next;
        }
        // 如果需要恢复原状
        firstEnd->next = reverseList(secondHead);
        return true;
    }
};

复杂度分析

时间复杂度:O(n),其中 n 指的是链表的大小。

空间复杂度:O(1)。我们只会修改原本链表中节点的指向,而在堆栈上的堆栈帧不超过 O(1)。