Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define MAXMES 257
- #define CHUNK 128
- void checkAlloc(void *p) {
- if (p == NULL) {
- perror("");
- exit(-1);
- }
- }
- typedef struct {
- int id;
- char message[MAXMES];
- } Info;
- typedef struct {
- int front, rear, mem;
- Info *buffer;
- } Queue;
- Queue mkQ() {
- Queue q = {0, 0, 0, NULL};
- return q;
- }
- void enq(Queue *q, Info info) {
- if (q->mem == q->rear) {
- q->mem += CHUNK;
- q->buffer = realloc(q->buffer, q->mem * sizeof(Info));
- checkAlloc(q->buffer);
- }
- q->buffer[q->rear++] = info;
- }
- int isEmpty(Queue q) {
- return q.rear == q.front;
- }
- Info deq(Queue *q) {
- if (isEmpty(*q)) {
- fprintf(stderr, "empty queue!\n");
- exit(-1);
- }
- return q->buffer[q->front++];
- }
- void freeQ(Queue q) {
- free(q.buffer);
- }
- int main(void) {
- Queue q = mkQ();
- static char message[MAXMES];
- for (int id = 1; fgets(message, MAXMES, stdin); id++) {
- Info info;
- info.id = id;
- message[strlen(message) - 1] = 0;
- strcpy(info.message, message);
- enq(&q, info);
- }
- while (!isEmpty(q)) {
- Info info = deq(&q);
- printf("received \"%s\" from %d\n", info.message, info.id);
- }
- freeQ(q);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement