zoukankan      html  css  js  c++  java
  • LeetCode "Palindrome Linked List"

    O(n) time O(n) space solution using stack<int>:

    class Solution 
    {
    public:
        bool isPalindrome(ListNode* head) 
        {
            if (!head || !head->next) return true;
    
            int cnt = 0;
            ListNode *p = head;
            while (p)
            {
                cnt++;
                p = p->next;
            }
    
            int pivot = cnt / 2;
            stack<int> stk;
            int i = 0;
            p = head;
            while (p)
            {
                if (i < pivot)
                {
                    stk.push(p->val);
                }
                else if ((cnt % 2) ?i > pivot : i>=pivot)
                {
                    if (stk.empty() || p->val != stk.top()) return false;
                    stk.pop();
                }
                p = p->next;
                i++;
            }
    
            return true;
        }
    };
    View Code

    O(1) space solution, we can reverse one half of it.

    class Solution
    {    
        ListNode* reverseList(ListNode* head) {
            if (!head) return nullptr;
            if (!head->next) return head;
    
            ListNode *p0 = head;
            ListNode *p1 = head->next;
            ListNode *p2 = p1 ? p1->next : nullptr;
    
            head->next = nullptr;
            while (p0 && p1)
            {
                p1->next = p0;
    
                p0 = p1;
                p1 = p2;
                p2 = p2 ? p2->next : nullptr;
            }
    
            return p0;
        }
    public:
        bool isPalindrome(ListNode* head)
        {
            if (!head) return true;
    
            // Split 
            ListNode *ps = head;
            ListNode *pf = ps->next;
            while (pf && pf->next && pf->next->next)
            {
                ps = ps->next;
                pf = pf->next->next;
            }
            ListNode *h2 = ps->next;
            ps->next = nullptr;
    
            //    Reverse
            h2 = reverseList(h2);
            while (head && h2)
            {
                if (head->val != h2->val) return false;
                head = head->next;
                h2 = h2->next;
            }
            return true;
        }
    };
    View Code
  • 相关阅读:
    ABP-AsyncLocal的使用
    ABP-多个DbContext实现事物更新
    ABP取其精华
    VS2019和net core 3.0(整理不全,但是孰能生巧)
    consul部署多台Docker集群
    Arcgis runtime sdk .net 二次开发
    C# 依赖注入 & MEF
    自动构建环境搭建
    C# 调用C/C++动态链接库,结构体中的char*类型
    C# 调用C++DLL 类型转换
  • 原文地址:https://www.cnblogs.com/tonix/p/4634998.html
Copyright © 2011-2022 走看看