码迷,mamicode.com
首页 > 其他好文 > 详细

LC 1206. Design Skiplist

时间:2020-03-07 20:57:00      阅读:60      评论:0      收藏:0      [点我收藏+]

标签:bre   tco   图片   size   width   arc   code   add   ras   

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

标签:bre   tco   图片   size   width   arc   code   add   ras   

原文地址:https://www.cnblogs.com/FEIIEF/p/12436769.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!