aboutsummaryrefslogtreecommitdiff
path: root/sem1/algo/mm2/queue.c
blob: a93f76a4b2098e46cf0c6fc0efb4f2358dd08751 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define EFULL 2
#define EMPTY 3

/* Queue stuff */
typedef struct {
	int head;
	int tail;
	int len;
	int cap;
	int *buff;
} queue_t;

/* Queue functions */
int queue_init(queue_t *q, size_t cap) {
	/* Make the struct and set i to zero */
	memset(q, 0, sizeof(queue_t));

	/* Allocate the buffer */
	q->buff = (int *) malloc(cap * sizeof(int));
	if( q->buff == NULL ) {
		return 1;
	}

	/* Set capacity, the rest should be zero form memset */
	q->cap = cap;
	return 0;
}

void queue_free(queue_t *q) {
	/* Free the heap buffer */
	free(q->buff);
}

int queue_place(queue_t *q, int val) {
	/* Check if full */
	printf("len: %d\n", q->len);
	if( q->len >= q->cap) {
		printf("ERR: Full\n");
		return EFULL;
	}

	/* Add to queue */
	q->buff[q->head] = val;
	
	/* Increase values */
	q->head = (q->head+1) % q->cap;
	q->len++;

	return 0;
}

int queue_get(queue_t *q, int *val) {
	/* Check if empty */
	if( !q->len ) {
		printf("ERR: Empty\n");
		return EMPTY;
	}

	/* Read value */
	if( val != NULL ){
		*val = q->buff[q->tail];
	}

	/* Decrease values */
	q->tail = (q->tail+1) % q->cap;
	q->len--;

	return 0;
}

int main(void) {
	int in;
	char com;

	queue_t q;
	queue_init(&q, 16);

	for(;;) {
		/* Read a command */
		scanf("%c", &com);

		if( com == 'w') {
			printf("> ");
			scanf("%d", &in);
			queue_place(&q, in);
		} else if( com == 'r' ) {
			queue_get(&q, &in);
			printf("%d\n", in);
		} else if( com == 'q' ) {
			break;
		}
	}

	queue_free(&q);
	
}