代码实现简单,记录一下
c
typedef struct List {
int key;
int val;
struct List *prev;
struct List *next;
}DlistNode;
typedef struct Dlist {
DlistNode *head;
DlistNode *tail;
int len;
}Dlist;
Dlist *InitDlist(void) {
Dlist *dl = (Dlist *)malloc(sizeof(Dlist));
dl->head = (DlistNode *)malloc(sizeof(DlistNode));
dl->tail = (DlistNode *)malloc(sizeof(DlistNode));
dl->tail->next = NULL;
dl->tail->prev = dl->head;
dl->head->prev = NULL;
dl->head->next = dl->tail;
dl->len = 0;
return dl;
}
DlistNode *DlistPush(Dlist *dl, int key, int val) {
// printf("add: %d %d\n", key, val);
DlistNode *p = (DlistNode *)malloc(sizeof(DlistNode));
p->key = key;
p->val = val;
p->next = dl->tail;
p->prev = dl->tail->prev;
dl->tail->prev = p;
p->prev->next = p;
dl->len++;
return p;
}
DlistNode *DlistPop(Dlist *dl) {
DlistNode *p = dl->head->next;
// printf("del: %d %d\n", p->key, p->val);
dl->head->next = dl->head->next->next;
dl->head->next->prev = dl->head;
dl->len--;
return p;
}
int DlistDel(Dlist *dl, DlistNode *d) {
// printf("del: %d %d\n", d->key, d->val);
DlistNode *p = d->prev, *q = d->next;
p->next = q;
q->prev = p;
int res = d->val;
free(d);
dl->len--;
return res;
}
使用
c
# 初始化
Dlist *dl = InitDlist();
# push
DlistPush(dl, 0, 1);
# Pop
DlistPop(dl);
# 删除指定元素
DlistNode *d = xxx;
DlistDel(dl, d);