I'm trying to understand the function "enqueue" my professor did but i don't get some steps.
struct queue_node {
int item;
struct queue_node* next;
};
typedef struct queue_node* queue;
int enqueue (queue* tail, int i) {
queue n;
queue *iter;
n = (queue)malloc(sizeof(struct queue_node));
if (!n) return 1;
n->item = i;
n->next = NULL;
for (iter=tail; *iter != NULL; iter = &((*iter)->next)
;
*iter = n;
return 0;
}
First of all that "typedef struct queue_node* queue;" is confusing me so i tried to reinterpret the code this way (please correct the code if i'm wrong)
struct queue_node {
int item;
struct queue_node* next;
};
typedef struct queue_node queue;
int enqueue (queue **tail, int i) {
queue *n;
queue **iter;
n = (queue)malloc(sizeof(struct queue_node));
if (!n) return 1; --->what does that mean?
n->item = i;
n->next = NULL;
for (iter=tail; **iter != NULL; iter = &((*iter)->next)--->last part of the for is unclear to me... can i rewrite it as "iter = **((iter)->next)"?
;
*iter = n; -->this is the part i don't really get...
return 0;
}
So by the way before trying to read the solution of my professor i tried to do an "enqueue" function on my own
typedef struct node{
int value;
struct node *next;
}node;
void enqueue(node *head,int data){
if(head->next != NULL){
enqueue(head->next,data);
}
node *new=NULL;
new=malloc(sizeof(node));
new->value=data;
new->next=NULL;
head->next=new;
}
Is this good? or i can't use it? Thank you all in advance for the help