Skip to content

Instantly share code, notes, and snippets.

@welljsjs
Last active February 24, 2018 22:05
Show Gist options
  • Save welljsjs/f2882ab68cd631432ee3f2564e331735 to your computer and use it in GitHub Desktop.
Save welljsjs/f2882ab68cd631432ee3f2564e331735 to your computer and use it in GitHub Desktop.
Implemented a queue in C.
//
// main.c
// Queue
//
// Created by Julius Schmidt on 24.02.18.
// Copyright © 2018 Julius Schmidt. All rights reserved.
//
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
typedef struct node {
struct node* nextNode;
void* content;
} node;
typedef struct queue {
node* head;
node* tail;
size_t size;
} queue;
void enqueue(queue*, void*);
bool empty(queue*);
void dequeue(queue*);
int main(int argc, const char * argv[]) {
queue q;
int exampleElement = 5;
int exampleElement2 = 56;
int exampleElement3 = 100;
enqueue(&q, &exampleElement);
enqueue(&q, &exampleElement2);
enqueue(&q, &exampleElement3);
dequeue(&q);
printf("Size of queue (count elements): %zu\n", q.size);
printf("First element in queue (cast as integer): %d\n", *((int*)q.head->content));
printf("Second element in queue (cast as integer): %d\n", *((int*)q.head->nextNode->content));
}
void enqueue(queue* queue, void* element) {
node* newnode = calloc(1, sizeof(node));
newnode->content = element;
if (empty(queue)) {
queue->head = newnode;
queue->tail = newnode;
queue->size = 1;
} else {
queue->tail->nextNode = newnode;
queue->tail = newnode;
queue->size++;
}
}
void dequeue(queue* queue) {
if (!empty(queue)) {
node* oldHead = queue->head;
queue->head = queue->head->nextNode;
free(oldHead);
oldHead = NULL;
}
}
bool empty(queue* queue) {
return queue->head == NULL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment