Created
August 12, 2020 18:02
-
-
Save cs-fedy/8121b61958bcd35be6e2391adc672253 to your computer and use it in GitHub Desktop.
Queue implementation using linked list in C.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <assert.h> | |
struct Node { | |
int key; | |
Node * next; | |
}; | |
struct Queue { | |
Node * head; | |
Node * tail; | |
}; | |
typedef struct Node Node; | |
typedef struct Queue Queue; | |
Queue * create_queue(void); | |
unsigned is_empty(Queue *); | |
int get_head(Queue *); | |
void enqueue(Queue *, int); | |
void dequeue(Queue *); | |
Queue * create_queue() { | |
Queue * qu = malloc(sizeof(Queue)); | |
qu -> head = NULL; | |
qu -> tail = NULL; | |
return qu; | |
} | |
unsigned is_empty(Queue * qu) { | |
return qu -> head == NULL && qu -> tail == NULL; | |
} | |
int get_head(Queue * qu) { | |
assert(!is_empty(qu)); | |
return qu -> head -> key; | |
} | |
void enqueue(Queue * qu, int key) { | |
Node * nd = malloc(sizeof(Node)); | |
nd -> key = key; | |
nd -> next = NULL; | |
if (is_empty(qu)) { | |
qu -> head = nd; | |
qu -> tail = nd; | |
} else { | |
qu -> tail -> next = nd; | |
qu -> tail = nd; | |
} | |
} | |
void dequeue(Queue * qu) { | |
assert(!is_empty(qu)); | |
Node * tmp_node = qu -> head; | |
qu -> head = tmp_node -> next; | |
free(tmp_node); | |
if (qu -> head == NULL) | |
qu -> tail = NULL; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment