简体   繁体   中英

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 returning  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;
...

你删除元素时,你必须检查head-> next == NULL或者是否。如果这是真的那么你必须将tail设置为NULL,因为这必须是链表中的最后一个节点。希望这会使你的程序运行。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM