Attempted to separate the snippets of code to small functions and each set of functions have its own file. Also made some improvements by using pools instead of constantly mallocing space.
This commit is contained in:
15 files changed
+561
-289
No files matched your search
+63
@@ -0,0 +1,63 @@
|
||||
#include "queue.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
static Node* q_front = NULL;
|
||||
static Node* q_back = NULL;
|
||||
static int current_size = 0;
|
||||
static int capacity = 0;
|
||||
|
||||
void q_init(int max_elements) {
|
||||
capacity = max_elements;
|
||||
q_front = NULL;
|
||||
q_back = NULL;
|
||||
current_size = 0;
|
||||
}
|
||||
|
||||
void q_push(Node* n) {
|
||||
if (current_size >= capacity) return; /* Pool safety */
|
||||
|
||||
/* Exact logic from your 'enqueue' function */
|
||||
n->next = NULL;
|
||||
if (!q_back) {
|
||||
q_front = q_back = n;
|
||||
} else {
|
||||
q_back->next = n;
|
||||
q_back = n;
|
||||
}
|
||||
current_size++;
|
||||
}
|
||||
|
||||
Node* q_pop() {
|
||||
/* Exact logic from your 'dequeue' function */
|
||||
if (!q_front) return NULL;
|
||||
|
||||
Node* r = q_front;
|
||||
q_front = q_front->next;
|
||||
|
||||
if (!q_front) {
|
||||
q_back = NULL;
|
||||
}
|
||||
|
||||
r->next = NULL; /* Clean up the link */
|
||||
current_size--;
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
int q_size() {
|
||||
return current_size;
|
||||
}
|
||||
|
||||
void q_clear() {
|
||||
q_front = NULL;
|
||||
q_back = NULL;
|
||||
current_size = 0;
|
||||
}
|
||||
|
||||
void q_destroy() {
|
||||
q_front = NULL;
|
||||
q_back = NULL;
|
||||
current_size = 0;
|
||||
capacity = 0;
|
||||
}
|
||||
Reference in new issue
Block a user