zoukankan      html  css  js  c++  java
  • LC 1206. Design Skiplist

    link

    class Skiplist {
    public:
        struct Node{
            int key;
            Node* down;
            Node* next;
            Node(int k, Node* d, Node *n){
                key=k;
                down=d;
                next=n;
            }
        };
        Node* head;
        Skiplist() {
            head=new Node(-1,NULL,NULL);
        }
        
        bool search(int target) {
            Node* p=head;
            while(p){
                Node* ne=p->next;
                while(ne!=NULL && ne->key<target){
                    p=p->next;
                    ne=ne->next;
                }
                if(ne!=NULL && target==ne->key) return true;
                p=p->down;
            }
            return false;
        }
        
        void add(int num) {
            vector<Node*> nodes;
            Node* p=head;
            Node* downNode=NULL;
            while(p){
                Node* ne=p->next;
                while(ne!=NULL && num>ne->key){
                    p=p->next;
                    ne=ne->next;
                }
                nodes.push_back(p);
                p=p->down;
            }
            for(int i=nodes.size()-1;i>=0;--i){
                auto cur=nodes[i];
                Node* newNode=new Node(num,downNode,NULL);
                newNode->next=cur->next;
                cur->next=newNode;
                downNode=newNode;
                bool up=((rand()&1)==0);
                if(!up) break;
                if(i==0){
                    Node* newLayerNode=new Node(num,downNode,NULL);
                    head=new Node(-1,head,newLayerNode);
                }
            }
        }
        
        bool erase(int num) {
            bool flag=false;
            Node* p=head;
            while(p){
                Node* ne=p->next;
                while(ne!=NULL && num>ne->key){
                    p=p->next;
                    ne=ne->next;
                }
                if(ne!=NULL && num==ne->key){
                    p->next=p->next->next;
                    flag=true;
                }
                p=p->down;
            }
            return flag;
        }
    };
    
    /**
     * Your Skiplist object will be instantiated and called as such:
     * Skiplist* obj = new Skiplist();
     * bool param_1 = obj->search(target);
     * obj->add(num);
     * bool param_3 = obj->erase(num);
     */
  • 相关阅读:
    深入理解Linux修改hostname
    Linux开发环境必备十大开发工具
    管理员必备的几个Linux系统监控工具
    Solaris&&QNX® Neutrino®&&OpenVMS&&FreeBSD&&AIX
    ansible来了
    Cobbler系统安装备用链接
    Web安全
    在Eclipse/STS中使用EclEmma进行覆盖率检查
    C#中使用扩展方法
    Winform中Textbox的使用
  • 原文地址:https://www.cnblogs.com/FEIIEF/p/12436769.html
Copyright © 2011-2022 走看看