• [LeetCode] Palindrome Linked List


     

    Given a singly linked list, determine if it is a palindrome.

    Follow up:
    Could you do it in O(n) time and O(1) space?

     判断回文链表

    思路:由于链表无法像数组、字符串一样直接定位到中间索引,所以要利用快慢指针来确定中心元素。再将链表的前半部分的元素放入栈stk中,这时存在一个问题,就是如果链表元素为奇数,则将最中心的元素也放入了stk中,而这个元素不参与之后的比较,所以需要将它弹出stk,如果链表元素为偶数,就不需要对此操作了。接下来依次弹出stk中元素与后半部分元素比较,判断每个对应的元素是否相等,如果不等就返回false。则该链表不是回文链表。

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        bool isPalindrome(ListNode* head) {
            if (head == nullptr || head->next == nullptr)
                return true;
            ListNode* fast = head;
            ListNode* slow = head;
            stack<ListNode*> stk;
            stk.push(head);
            while (fast->next != nullptr && fast->next->next != nullptr) {
                fast = fast->next->next;
                slow = slow->next;
                stk.push(slow);
            }
            if (fast->next == nullptr)
                stk.pop();
            while (slow->next != nullptr) {
                slow = slow->next;
                ListNode* tmp = stk.top();
                stk.pop();
                if (tmp->val != slow->val)
                    return false;
            }
            return true;
        }
    };
    // 23 ms
     
  • 相关阅读:
    linux批量远程多服务器FTP并下载文件的脚本
    NPM更换国内源
    Win10禁用无用的服务
    JS测试
    FastAdmin导出
    VScode全局设置
    Vue路由history模式
    kill_devtmpfsi
    获取域名URL
    Axios去除Respones中的config、headers、request
  • 原文地址:https://www.cnblogs.com/immjc/p/7777323.html
Copyright © 2020-2023  润新知