c - 自动删除双向链表中的元素

标签 c doubly-linked-list

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

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)

关于c - 自动删除双向链表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37101969/

相关文章:

c - 如何使用 printf() 格式化字符串以在输出中获得相等的长度

c - 我的 Checkprime.c 程序有什么问题?

c - 在不使用循环的情况下将char *转换为C中的大写

Java : add node in sorted doubly linked list

java - BufferedReader 输入到双向链表

c - 如何检查字符串是否为数字?

c - NOP 字符 0x90 的 printf 在 x86_64 和 i686 上编译时不同

java - 如何在自定义 OrderedLinkedList 类中显示从列表中删除了哪些元素?

java - 双向链表的排序方法

c++ - 无法释放C++中双链表中的节点