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
  • 相关阅读:
    验证码识别思路
    chrome插件 图片搜索(20130602更新版本v2.0)
    CoffeeScript实现BF解释器
    浏览器几种高度宽度
    javascript Event事件
    浮躁的心
    前端页面跨域访问
    firefox浏览器兼容event事件方法
    转:Java Annotation详解
    javascript void(0)问题【转】
  • 原文地址:https://www.cnblogs.com/tonix/p/4634998.html
Copyright © 2011-2022 走看看