当前位置:网站首页>Bidirectional linked list simple template (pointer version)

Bidirectional linked list simple template (pointer version)

2022-06-11 07:30:00 Master. Yi

Freshman year … And began to lay the foundation for the program ( Dream back to the first day of junior high school
I found that I haven't used the pointer for the problems that I have typed for several years , Let's write the linked list of the pointer version … It turned out to be disgusting
At the beginning of writing, I didn't insert a minimax value at the beginning and end , Then, when inserting and deleting, it is necessary to judge a lot of null pointers at the beginning and end …
Then it suddenly occurred to me to do Splay When the method … Insert a minimax … Instant harmony 100 times ..

#include<cstdio>
struct link{
    
    int id,val;
    link *pre,*nxt;
    link(int id=0,int val=0,link *pre=0,link *nxt=0):id(id),val(val),pre(pre),nxt(nxt){
    }
};
void insert(link *p,int idx,int w){
    
    link *q;
    while((q=p->nxt)->id<idx) p=q;
    if(q->id==idx) q->val=w;
    else{
    
        link *t=new link(idx,w,p,q);
        p->nxt=q->pre=t;
    }
}
void del_by_id(link *p,int idx){
    
    link *q;
    while((q=p->nxt)->id<idx) p=q;
    if(q->id==idx){
    
        p->nxt=q->nxt,q->nxt->pre=p;
        delete q;
    }
}
void Print(link *p){
    
    for(p=p->nxt;p->nxt!=NULL;p=p->nxt) printf("id: %d val: %d\n",p->id,p->val);
}
void DelList(link *p){
    
    for(link *q;p!=NULL;p=q) {
    q=p->nxt; delete p;}
}
int main()
{
    
    link *head=new link(-1e9,0,0,0),*tail=new link(1e9,0,head,0);
    head->nxt=tail;
    insert(head,1,10);
    insert(head,5,50);
    insert(head,3,30);
    insert(head,-1,-10);
    del_by_id(head,3);
    del_by_id(head,4);
    Print(head);
    DelList(head);
}
原网站

版权声明
本文为[Master. Yi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203020520542729.html