234. 回文链表 ------ 对称检验栈、转化为数组用双指针、快慢指针找中间结点、递归

给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。

 

示例 1:


输入:head = [1,2,2,1]
输出:true
示例 2:


输入:head = [1,2]
输出:false
 

提示:

链表中节点数目在范围[1, 105] 内
0 <= Node.val <= 9
 

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

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/palindrome-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

对称栈:

/**
 * 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 {
public:
    bool isPalindrome(ListNode* head) {
        stack<int> stk;
        stk.push(head->val);
        ListNode* p = head;
        while (p) {
            stk.push(p->val);
            p = p -> next;
        }
        while (head) {
            if (stk.top() != head -> val) return false;
            stk.pop();
            head = head -> next;
        }
        return true;
    }
};

 

数组双指针;

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        vector<int> vals;
        while (head != nullptr) {
            vals.emplace_back(head->val);
            head = head->next;
        }
        for (int i = 0, j = (int)vals.size() - 1; i < j; ++i, --j) {
            if (vals[i] != vals[j]) {
                return false;
            }
        }
        return true;
    }
};

 

 快慢指针找中间结点+对称栈:

class Solution {
public:
    // 辅助栈
    bool isPalindrome(ListNode* head) {
        ListNode* slow = head;
        ListNode* fast = head;

        while (fast)
        {
            if (fast->next == nullptr)
                break;
            if (fast->next->next == nullptr)
                break;

            slow = slow->next;
            fast = fast->next->next;
        }
        // 拿到链表中间位置,将其后半部分入栈
        stack<int> s;
        ListNode* cur = slow->next; // 链表长度为偶数时,slow位于上一个中间节点,我们从下一个开始
        while (cur)
        {
            s.push(cur->val);
            cur = cur->next;
        }

        // 比较栈元素和链表元素是否相等
        while (!s.empty())
        {
            if (s.top() != head->val)
                return false;
            s.pop();
            head = head->next;
        }
        return true;
    }
};

 递归找到尾结点:

class Solution {
    ListNode* _head;
public:
    // 递归
    bool _isPalindrome(ListNode* head) {
        if (head == nullptr)
            return true;
        if (!_isPalindrome(head->next))
            return false;
        if (head->val != _head->val)
            return false;

        _head = _head->next;
        return true;
    }
    bool isPalindrome(ListNode* head) {
        _head = head;
        return _isPalindrome(head);
    }
};

 

posted @ 2022-11-16 10:41  slowlydance2me  阅读(11)  评论(0编辑  收藏  举报