I guess it helps if you copy the code correctly.
Code:
$ gcc -Wall foo.c
foo.c: In function ‘enqueue’:
foo.c:26:5: warning: statement with no effect [-Wunused-value]
head.last - item;
^
But it still doesn't work.
Code:
$ gcc -Wall foo.c
$ ./a.out
First element = 6295648
Last element = 2
EMPTY
Try this, which does work, and also removes that messy global variable.
Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct listItem {
int data;
struct listItem *next;
struct listItem *prev;
}LISTITEM;
typedef struct listHDR {
struct listItem *first;
struct listItem *last;
}LISTHDR;
void enqueue(LISTHDR *head,LISTITEM *item) {
if ( head->first == NULL ) {
head->first = head->last = item;
} else {
head->last->next = item;
item->prev = head->last;
head->last = item;
}
}
LISTITEM* dequeue(LISTHDR *head) {
LISTITEM *temp = NULL;
if ( head->first ) {
temp = head->first;
head->first = temp->next;
if ( head->first == NULL ) {
head->last = NULL;
}
}
return temp;
}
int main()
{
LISTHDR head = { 0, 0 };
LISTITEM *Temp;
for(int i = 0; i < 3; i++) {
Temp = malloc(sizeof(LISTITEM)); //!! no need to cast malloc in C
Temp->next = NULL;
Temp->prev = NULL;
Temp->data = i;
enqueue(&head,Temp);
}
printf("First element = %d\n", head.first->data);
printf("Last element = %d\n", head.last->data);
do {
Temp = dequeue(&head);
if(Temp != NULL) {
printf("Data: %d\n", Temp->data);
free(Temp);
}
else {
printf("EMPTY\n");
}
} while(Temp != NULL);
return 0;
}
$ ./a.out
First element = 0
Last element = 2
Data: 0
Data: 1
Data: 2
EMPTY
> Like I said further videos in this series make use of this tutorial
Look forward to more mistakes from this author then.