본문 바로가기
C and C++/C and C++ Examples

[C Example Code] queue를 활용한 환자의 우선 순위 나타내기: malloc(), queue, struct, point, void()

by Henry Cho 2023. 11. 29.
728x90

queue를 활용한 환자의 우선순위 나타내기: malloc(), queue, struct, point, void()

포스트 난이도: HOO_Junior


# Queue, Enqueue, Dequeue

이번 예제코드에서는 Queue (큐)를 활용한 우선순위를 나타내고 변경하는 결과를 살펴볼 수 있다. 예제코드 포스트이다 보니 큐에 대해서 이미 알고 있겠지만 간단히 Wrap-up 하자면 큐는 First in first out, 즉 FIFO 원칙을 따르는 데이터 구조이다. 따라서 큐에 추가 된 첫 번째 요소가 가장 먼저 제거되는 것을 의미한다. 해당 예제코드를 살펴보면 큐에 입력된 값을 변경하여 우선순위를 변경해 줄 수 있는데 이 부분이 기존의 값이 삭제되고 새로운 값이 추가된다고 볼 수 있다.

 

큐에는 Enqueue와 Dequeue가 존재하고 큐의 뒤 쪽에 요소를 추가하는 역할과 큐의 앞 쪽의 요소를 제거하는 기능을 담당한다. 또한 Peek의 경우는 큐 앞 요소를 제거하지 않고 반환하는 역할을 담당한다. 이 세가지 주요 요소들을 이해한다면 큐를 코드에서 쉽게 활용할 수 있다.

 

아래의 예제코드는 환자들의 우선순위를 바꿔주는 간단한 프로그램이다. 환자의 이름과 우선순위를 입력하고 나서 우선순위를 변경하거나 변경된 우선순위를 이름과 함께 출력이 가능하다. 여기서 중점적으로 봐야하는 부분은 큐가 어떤 식으로 작동해서 기존의 데이터와 추가된 데이터 간의 데이터가 어떻게 저장되는지이다. 따라서 각 void function에서 기능들이 어떤 식으로 작동이 되는지를 집중적으로 보고 이를 통해서 큐에 대한 복습이 가능하다. 아래의 예제코드 2번과 3번은 환자의 우선순위를 변경하고 입력한다는 가정하에 만들어진 코드이며, 예제코드 1번의 경우 큐에 대한 원리를 이해할 수 있도록 만든 예제코드이다.


#  Example Code #01

#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 100

struct Queue {
    int array[MAX_SIZE];
    int front;
    int rear;
};

void initializeQueue(struct Queue *queue) {
    queue->front = -1;
    queue->rear = -1;
}

int isEmpty(struct Queue *queue) {
    return (queue->front == -1 && queue->rear == -1);
}

int isFull(struct Queue *queue) {
    return (queue->rear + 1) % MAX_SIZE == queue->front;
}

void enqueue(struct Queue *queue, int value) {
    if (isFull(queue)) {
        printf("Queue is full. Cannot enqueue.\n");
        return;
    }

    if (isEmpty(queue)) {
        queue->front = 0;
        queue->rear = 0;
    } else {
        queue->rear = (queue->rear + 1) % MAX_SIZE;
    }

    queue->array[queue->rear] = value;
}

int dequeue(struct Queue *queue) {
    int dequeuedValue;

    if (isEmpty(queue)) {
        printf("Queue is empty. Cannot dequeue.\n");
        return -1;
    } else if (queue->front == queue->rear) {
       
        dequeuedValue = queue->array[queue->front];
        queue->front = -1;
        queue->rear = -1;
    } else {
        dequeuedValue = queue->array[queue->front];
        queue->front = (queue->front + 1) % MAX_SIZE;
    }

    return dequeuedValue;
}


int peek(struct Queue *queue) {
    if (isEmpty(queue)) {
        printf("Queue is empty. Cannot peek.\n");
        return -1;
    }

    return queue->array[queue->front];
}

int main() {
    struct Queue myQueue;
    initializeQueue(&myQueue);

    enqueue(&myQueue, 10);
    enqueue(&myQueue, 20);
    enqueue(&myQueue, 30);
    enqueue(&myQueue, 40);
    enqueue(&myQueue, 50);

    printf("Front element: %d\n", peek(&myQueue));

    printf("Dequeued: %d\n", dequeue(&myQueue));
    printf("Dequeued: %d\n", dequeue(&myQueue));
    printf("Dequeued: %d\n", dequeue(&myQueue));
    printf("Dequeued: %d\n", dequeue(&myQueue));

    enqueue(&myQueue, 40);

    printf("Front element: %d\n", peek(&myQueue));

    return 0;
}

Figure 1. Result of example code #01


#  Example Code #02

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct node {
    char data[20];
    int priority;
    struct node* next;
};

struct node* head = NULL;

void insert(char* val, int pri) {
    struct node* newNode = (struct node*)malloc(sizeof(struct node));
    int i = 0;

    while (val[i] != '\0') {
        newNode->data[i] = val[i];
        i++;
    }

    newNode->data[i] = '\0';
    newNode->priority = pri;

    if (head == NULL || pri > head->priority) {
        newNode->next = head;
        head = newNode;
    } else {
        struct node* ptr = head;

        while (ptr->next != NULL && ptr->next->priority >= pri) {
            ptr = ptr->next;
        }

        newNode->next = ptr->next;
        ptr->next = newNode;
    }
}

void display() {
    struct node* ptr = head;

    if (head == NULL) {
        printf("Queue is empty\n");
    } else {
        printf("  Priority Queue is:  ");

        while (ptr != NULL) {
            printf("|%s Pri:%d|  ", ptr->data, ptr->priority);
            ptr = ptr->next;
        }
    }
}

void search_change() {
    struct node* ptr = head;
    struct node* previousNode = NULL;
    char name[20];
    int match = 0;

    if (head == NULL) {
        printf("Queue is empty\n");
    } else {
        printf("Enter the name of the patient to search: ");
        scanf("%s", name);

        while (ptr != NULL) {
            int i = 0;
            match = 1;

            while (name[i] != '\0') {
                if (ptr->data[i] != name[i]) {
                    match = 0;
                    break;
                }
                i++;
            }

            if (match == 1) {
                if (head == ptr) {
                    head = head->next;
                    free(ptr);
                } else {
                    previousNode->next = ptr->next;
                    free(ptr);
                }

                int newPriority;
                printf("Enter the new priority for %s: ", name);
                scanf("%d", &newPriority);
                insert(name, newPriority);
                break;
            }

            previousNode = ptr;
            ptr = ptr->next;
        }

        if (match == 0) {
            printf("The person you are looking for not in the queue.\n");
        }
    }
}

int main() {
    int choice;
    while (1) {
        printf("\nEnter 1 to add a new patient, 2 to change the priority,\n3 to display the queue, Any other key to quit: ");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                char firstname[20];
                int priority;
                printf("  Enter patient's first name: ");
                scanf("%s", firstname);
                printf("  Enter patient's priority #: ");
                scanf("%d", &priority);
                insert(firstname, priority);
                break;
            case 2:
                search_change();
                break;
            case 3:
                display();
                break;
            default:
                printf("End of program!");
                exit(0);
        }
    }

    return 0;
}

Figure 2. Result of example code #02


# Example code #02

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct node {
    char data[20];
    int priority;
    struct node* next;
};

struct node* head = NULL;

void insert(char* val, int pri) {
    struct node* newNode = (struct node*)malloc(sizeof(struct node));
    int i = 0;

    while (val[i] != '\0') {
        newNode->data[i] = val[i];
        i++;
    }

    newNode->data[i] = '\0';
    newNode->priority = pri;

    if (head == NULL || pri > head->priority) {
        newNode->next = head;
        head = newNode;
    } else {
        struct node* ptr = head;

        while (ptr->next != NULL && ptr->next->priority >= pri) {
            ptr = ptr->next;
        }

        newNode->next = ptr->next;
        ptr->next = newNode;
    }
}

void display() {
    struct node* ptr = head;

    if (head == NULL) {
        printf("Queue is empty\n");
    } else {
        printf("Priority Queue is:\n");

        while (ptr != NULL) {
            printf("%s %d\n", ptr->data, ptr->priority);
            ptr = ptr->next;
        }
    }
}

void search_change() {
    struct node* ptr = head;
    struct node* previousNode = NULL;
    char name[20];
    int match = 0;

    if (head == NULL) {
        printf("Queue is empty\n");
    } else {
        printf("Enter the name of the patient to search: ");
        scanf("%s", name);

        while (ptr != NULL) {
            int i = 0;
            match = 1;

            while (name[i] != '\0') {
                if (ptr->data[i] != name[i]) {
                    match = 0;
                    break;
                }
                i++;
            }

            if (match == 1) {
                if (head == ptr) {
                    head = head->next;
                    free(ptr);
                } else {
                    previousNode->next = ptr->next;
                    free(ptr);
                }

                int newPriority;
                printf("Enter the new priority for %s: ", name);
                scanf("%d", &newPriority);
                insert(name, newPriority);
                break;
            }

            previousNode = ptr;
            ptr = ptr->next;
        }

        if (match == 0) {
            printf("Patient not found in the queue\n");
        }
    }
}

int main() {
    int choice;
    while (1) {
        printf("MENU:\n");
        printf("1. Insert patient\n2. Search and change priority\n3. Display priority queue\n4. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                char firstname[20];
                int priority;
                printf("Enter patient's name: ");
                scanf("%s", firstname);
                printf("Enter patient's priority: ");
                scanf("%d", &priority);
                insert(firstname, priority);
                break;
            case 2:
                search_change();
                break;
            case 3:
                display();
                break;
            default:
                printf("End of program\n");
                exit(0);
        }
    }

    return 0;
}

Figure 3. Result of example code #03


#  github link

Example code #01

https://github.com/WhoisHOO/HOOAI/blob/main/C%20Examples/example_queue_dequeue_enqueue

 

Example code #02

https://github.com/WhoisHOO/HOOAI/blob/main/C%20Examples/simple_queue_patient

 

Example code #03

https://github.com/WhoisHOO/HOOAI/blob/main/C%20Examples/simple_queue_patient_2


 

728x90

댓글