problem is, when I call function initDeque
to create deque, function have to check if deque was already initialized. My thought was having variable bool isInit
in deque's structure and check if isInit
is true(initiated) / false(not initiated). But the problem is, if I call initDeque
more than one time, it initiates deque again. Here's the code:
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!");
}
}
and the struct:
typedef struct{
link front;
link rear;
bool isInit;
}deque;
My thought is that when I allocate memory in the first place, it removes all data stored in front; rear; isInit;
. What should I do?
You could try something like this:
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;
}
As has been mentioned in many places on this post, this is a weird implementation.
Normally with this kind of data structure you'd have create(), destroy(deque *d), queue(deque *d), dequeue(deque *d) functions.
At the top of each function you'd have a NULL check (except for create)