Advertisement
STANAANDREY

tema tp 3-4

Mar 12th, 2023
737
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.24 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #define MAXMES 257
  5. #define CHUNK 128
  6.  
  7. void checkAlloc(void *p) {
  8.   if (p == NULL) {
  9.     perror("");
  10.     exit(-1);
  11.   }
  12. }
  13.  
  14. typedef struct {
  15.   int id;
  16.   char message[MAXMES];
  17. } Info;
  18.  
  19. typedef struct {
  20.   int front, rear, mem;
  21.   Info *buffer;
  22. } Queue;
  23.  
  24. Queue mkQ() {
  25.   Queue q = {0, 0, 0, NULL};
  26.   return q;
  27. }
  28.  
  29. void enq(Queue *q, Info info) {
  30.   if (q->mem == q->rear) {
  31.     q->mem += CHUNK;
  32.     q->buffer = realloc(q->buffer, q->mem * sizeof(Info));
  33.     checkAlloc(q->buffer);
  34.   }
  35.   q->buffer[q->rear++] = info;
  36. }
  37.  
  38. int isEmpty(Queue q) {
  39.   return q.rear == q.front;
  40. }
  41.  
  42. Info deq(Queue *q) {
  43.   if (isEmpty(*q)) {
  44.     fprintf(stderr, "empty queue!\n");
  45.     exit(-1);
  46.   }
  47.   return q->buffer[q->front++];
  48. }
  49.  
  50. void freeQ(Queue q) {
  51.   free(q.buffer);
  52. }
  53.  
  54. int main(void) {
  55.   Queue q = mkQ();
  56.   static char message[MAXMES];
  57.   for (int id = 1; fgets(message, MAXMES, stdin); id++) {
  58.     Info info;
  59.     info.id = id;
  60.     message[strlen(message) - 1] = 0;
  61.     strcpy(info.message, message);
  62.     enq(&q, info);
  63.   }
  64.   while (!isEmpty(q)) {
  65.     Info info = deq(&q);
  66.     printf("received \"%s\" from %d\n", info.message, info.id);
  67.   }
  68.   freeQ(q);
  69.   return 0;
  70. }
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement