简体   繁体   中英

c - Implementation of queue using linked list

I tried to do implementation of queue by using linked list, but there always occurred error: incompatible types in assignment and assignment makes pointer from integer without a cast.

Here is my code:

#include <stdlib.h>
#include <stdio.h>
#include "Queue.h"

struct QUEUE_ELEMENT{
int element;
struct QUEUE_ELEMENT *next;
};

int size;
struct QUEUE_ELEMENT *head, *tail;

void initQueue(){

    head = NULL;
    tail = NULL;
    size = 0;

}       // void initQueue()



int queueEmpty(void) {

return (head == NULL && tail == NULL);

}   // int queueEmpty(void)





int enqueue(QUEUE_ELEMENT e) {
struct QUEUE_ELEMENT *temp;
if (tail == NULL){
    tail -> next = NULL;
    tail -> element = e;
    head = tail;
}
else {
    temp = malloc(sizeof(QUEUE_ELEMENT));
    tail -> next = temp;
    temp -> element = e;
    temp -> next = NULL;
    tail = temp;
}
return size++;

}   //  int enqueue(QUEUE_ELEMENT e)





int dequeue(QUEUE_ELEMENT *e){
struct QUEUE_ELEMENT *temp;
temp = malloc(sizeof(QUEUE_ELEMENT));

if (queueEmpty() != 0 ){
    temp = head;
    if(temp -> next != NULL){
    temp = temp -> next;
    free(head);
    head = temp;
    }
    else{
        free(head);
        head = NULL;
        tail = NULL;
    }
}
    return size--;


}   //  int dequeue(QUEUE_ELEMENT *e)

I revised my code a lot.

Why 'tail -> element = e;' in enqueue() occurs error 'incompatible types in assignment'? How can I fix it?

Is it a homework or for a real need? For the first one I won't say anything. But if you need it in practice, it's better to use already implemented solution.

There is a popular style where, in a linked list, head looks like a usual entry and the only thing which distinguishes it is the head pointer value itself. The first good example is Linux linked lists implementation ( a description ). Its specifics is a trick to get the whole entry address from its link member. This one is trivial to study and can answer your goals immediately.

The second good example is BSD list and queue macro set (a manpage ; particularly, you could start with TAILQ macro set). It's more cumbersome due to some tricks (eg forward pointers address link field but backward pointers address the whole structure) but still efficient.

I hope both can satisfy you and prevent reinventing a wheel :)

You are assigning tail->element , which is an int, to e which is a QUEUE_ELEMENT . if you want to access the element in e you have to deference it like you did with tail first. so tail->element = e->element

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