检查链表是否初始化

标签 c linked-list deque

问题是,当我调用函数 initDeque 来创建双端队列时,函数必须检查双端队列是否已经初始化。我的想法是在双端队列的结构中使用变量 bool isInit 并检查 isInit 是否为 true(已启动)/false(未启动)。但问题是,如果我多次调用 initDeque,它会再次启动双端队列。这是代码:

int initDeque(deque *d){ //Create new deque
    d = (deque*)malloc(sizeof(deque));
    if ((d->isInit)==false){

        if (!d) {
            perror("malloc");
            exit(EXIT_FAILURE);
        }
        d->isInit=true;
        d->front=NULL;
        d->rear=NULL;
        return d;
    } else {
        printf("Deque is already initialized!");
    }
}

和结构:

typedef struct{
    link front;
    link rear;
    bool isInit;
}deque;

我的想法是,当我首先分配内存时,它会删除存储在 front 中的所有数据;后部;初始化;。我该怎么办?

最佳答案

你可以尝试这样的事情:

deque* initDeque(deque *d){ //Create new deque
    if(d == NULL){
       d = (deque*)malloc(sizeof(deque));
       d->isInit = false;
    }
    if ((d->isInit)==false){ 
        if (!d) {
            perror("malloc");
            exit(EXIT_FAILURE);
        }
        d->isInit=true;
        d->front=NULL;
        d->rear=NULL;
    } else 
        printf("Deque is already initialized!");
    return d;
}

正如这篇文章中许多地方所提到的,这是一个奇怪的实现。

通常,对于这种数据结构,您会有 create()、destroy(deque *d)、queue(deque *d)、dequeue(deque *d) 函数。

在每个函数的顶部都有一个 NULL 检查(创建除外)

关于检查链表是否初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29168133/

相关文章:

c++ - 使用链表对多项式进行匹配、加法和乘法

python - 检查链表是否是回文。找不到问题

java - 可迭代双端队列 NullPointerException

c++ - 尝试让 while 循环工作,当输入符号而不是字符时,该循环会中断

我们可以这样传递结构成员吗?

c - 程序段最小化 - if, else

c++ - 在双端队列 C++ 中将所有元素从一个列表传输到另一个列表

c - 如何使用 -lm -pthread 参数在 Netbeans 中编译 C 项目?

java - 如何对 LinkedHashMap 中的重复键值求和?

python - 如何在双端队列中打印项目(python)