问题是,当我调用函数 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/