双 link 列表中的自动删除元素

auto-deleting element in doubly link list

经过一定数量的步骤后,加载的(特定)元素应该在 execution/run 时间被(自动)删除。我想预先定义它以便它可以双倍执行自动删除链表

void del_begin()
{
  struct node *temp;

 if(start==NULL)
      return;
    else
    { temp=start;
        start=start->next;
                start->prev=NULL;
        printf("Unloaded Wagon =%s ",temp->num);
        free(temp);
    }

以下代码实现了一个双向链表,其中每个元素都可以分配一个生命周期值。每次调用 insert 都会减少生命周期 1。如果一个节点的生命周期为 0 ,它将被从列表中删除。生命周期值为负的节点将被忽略,因此永远不会从列表中删除。

#include <stdio.h>
#include <stdlib.h>

struct dll{
    struct node* head;
};

struct node {
    struct node* next;
    struct node* prev;
    int value;
    int lifetime;

};

void insert(struct dll*, int, int); // insert a new node
void step(struct dll*); // decrease the lifetime by one and remove "dead" nodes
void print(struct dll*); // print the nodes and their lifetime

int main(void) {
    struct dll* dll = malloc(sizeof(struct dll));
    dll->head = NULL;
    insert(dll, 1, -1);
    insert(dll, 2, 5);
    insert(dll, 3, 3);
    insert(dll, 4, 0);
    insert(dll, 5, 1);
    print(dll);
}

void insert(struct dll* dll, int value, int lifetime) {
    print(dll);
    step(dll);
    struct node* n = malloc(sizeof(struct node));
    n->value = value;
    n->lifetime = lifetime;
    if(dll->head == NULL) {
        dll->head = n;
        n->prev = dll->head;
        n->next = dll->head;
    } else {
        n->prev = dll->head->prev;
        dll->head->prev->next = n;
        dll->head->prev = n;
        n->next = dll->head;
    }
}

void step(struct dll* dll) {
    if(dll->head != NULL) {
        struct node* n = dll->head;
        do{
            if(n->lifetime == 0) {
                // remove the node
                struct node* next = n->next;
                n->prev->next = n->next;
                n->next->prev = n->prev;
                free(n);
                n = next;
            } else if(n->lifetime > 0){
                // decrease lifetime by one
                n->lifetime = n->lifetime - 1;
                n = n->next;
            } else {
                n = n->next;
            }
        } while(n != dll->head);
    }
}

void print(struct dll* dll) {
    if(dll->head != NULL) {
        struct node* n = dll->head;
        do{
            printf("%d(%d) ", n->value, n->lifetime);
            n = n->next;
        } while(n != dll->head);
    }
    printf("\n");
}

执行代码时打印出以下内容:

1(-1)
1(-1) 2(5)
1(-1) 2(4) 3(3)
1(-1) 2(3) 3(2) 4(0)
1(-1) 2(2) 3(1) 5(1)