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
  • 相关阅读:
    o gdb
    net -t struct ifreq
    file -x stat()-fstat()-lstat()
    I/O -x fcntl()
    I/O -x dup() dup2()
    14条---注意点
    user -x userid
    err -x perror() strerror()
    苹果电脑挂载NTFS移动硬盘
    ASP.NET Core之EF Core学习笔记
  • 原文地址:https://www.cnblogs.com/tonix/p/4634998.html
Copyright © 2011-2022 走看看