one-file-projects/linkedqueue.c

85 lines
1.4 KiB
C
Raw Permalink Normal View History

2016-02-21 16:15:08 +01:00
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef struct node {
int element;
struct node* next;
} Node;
typedef struct queue {
Node* head;
Node* tail;
} *Queue;
Queue qCreate() {
Queue q = malloc(sizeof(struct queue));
q->head = NULL;
q->tail = NULL;
return q;
}
int qEmpty(Queue q) {
return q->head == NULL;
}
void qPush(Queue q, int element) {
Node * n = malloc(sizeof(Node));
n->element = element;
n->next = NULL;
if(qEmpty(q)) {
q->head = q->tail = n;
} else {
q->tail->next = n;
q->tail = n;
}
}
int qPop(Queue q) {
assert(!qEmpty(q));
Node* n = q->head;
q->head = n->next;
if(q->head == NULL) {
q->tail == NULL;
}
int element = n->element;
free(n);
return element;
}
void qClear(Queue q) {
Node* iter = q->head;
Node* tmp;
while(iter != NULL) {
tmp = iter;
iter = iter->next;
free(tmp);
}
q->head = NULL;
q->tail = NULL;
}
void qFree(Queue q) {
qClear(q);
free(q);
}
int main( int argc, char *argv[] ) {
Queue q = qCreate();
for(int i = 0; i < 10; i++) {
qPush(q,i*i);
}
while(!qEmpty(q)) printf("%d ", qPop(q));
printf("\n");
for(int i = 0; i < 10; i++) qPush(q,i);
for(int i = 0; i < 5; i++) qPop(q);
printf("%d\n", qPop(q));
qClear(q);
assert(qEmpty(q));
qFree(q);
return 0;
}