Queue implementation with linked lists in C
Below is the implementation of my queue, which has functionality of enqueueing and dequeing from the Queue. Because of some reason it is crashing with no clues(where it is crashing), as the code is running on android. I suspect with my queue code. If you guys have any clue, what's wrong with my code, please give me an idea.
Thanks for any help.
Here is my C Code :
int qLast = 0;
typedef struct phoneSt PhoneStructure;
typedef struct{
PhoneStructure Phone;
struct phoneQ *next;
}phoneQ;
phoneQ *headElement = NULL; /* front pointer in queue*/
phoneQ *tailElement = NULL; /* rear pointer in queue */
void enqueue_Phone(PhoneStructure Frame)
{
phoneQ *newnode; /* New node to be inserted */
newnode=(phoneQ*)av_malloc(sizeof(phoneQ));
newnode->next=NULL;
newnode->Phone=Frame;
qLast++;
if(headElement==NULL && tailElement==NULL)
{
headElement=newnode;
tailElement=newnode;
}
else
{
tailElement->next=newnode;
tailElement=newnode;
}
__android_log_print(ANDROID_LOG_DEBUG, "myphone.c", "Queue is having %d element", qLast);
}
PhoneStructure dequeue_Phone()
{
phoneQ *delnode; /* Node to be deleted */
PhoneStructure Frame;
__android_log_write(ANDROID_LOG_DEBUG, "myplayer.c", "In dequeue_Phone");
if(headElement==NULL && tailElement==NULL){
__android_log_write(ANDROID_LOG_ERROR, "myphone.c", "Queue is empty to delete any element");
}
else
{
__android_log_write(ANDROID_LOG_DEBUG, "myphone.c", "In dequeue queue is not empty");
delnode=headElement;
headElement=headElement->next;
Frame = delnode->Phone;
av_free(delnode);
qLast--;
}
__android_log_print(ANDROID_LOG_DEBUG, "myphone.c", "In dequeue_Phone ret开发者_开发百科urning remaining %d",qLast);
return Frame;
}
When you empty the queue you do not set tailElement to NULL. Next time you enqueue, headElement will remain null, and you will access the deleted tailElement which may crash. If it doesn't, when you dequeue, you access headElement->next, which will crash.
...
headElement=headElement->next;
if (!headElement)
tailElement=NULL;
Frame = delnode->Phone;
...
When you are deleting the element you must make a check whether head->next==NULL or not.Since if this is true then you must set tail to NULL as this is must be last node in the linked list.Hope this would make your program run.
精彩评论