LC 1206. Design Skiplist

Posted feiief

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
 */

 

以上是关于LC 1206. Design Skiplist的主要内容,如果未能解决你的问题,请参考以下文章

[LC] 362. Design Hit Counter

[LC] 170. Two Sum III - Data structure design

[LC] 211. Add and Search Word - Data structure design

代写MATLAB编程- MATLAB编程代写Design a pushdown automata (PDA)

HotKey 触发 Ant Design Select 开始搜索

SkipList理解