선입선출 (FIFO: First-In First-Out)
전단(Front) : 삭제가 일어나는 곳.
create(max_size) ::=
최대 크기가 max_size인 공백큐를 생성한다.
init(q) ::=
큐를 초기화한다.
is_empty(q) ::=
if (size == 0) return TRUE;
else return FALSE;
is_full(q) ::=
if (size == max_size) return TRUE;
else return FALSE;
enqueue(q, e) ::=
if (is_full(q)) queue_full 오류;
else q의 끝에 e를 추가한다.
dequeue(q) ::=
if (is_empty(q)) queue_empty 오류;
else q의 맨 앞에 있는 e를 제거하여 반환한다.
peek(q) ::=
if (is_empty(q)) queue_empty 오류;
else q의 맨 앞에 있는 e를 읽어서 반환한다.
1차원 배열을 사용하여 먼저 들어온 데이터가 먼저 나가는 선입선출(FIFO, First-In First-Out) 구조의 자료구조.
#include <stdio.h>
#include <stdlib.h>
#define MAX_QUEUE_SIZE 5
typedef int element;
typedef struct { //선형 큐 타입
int front; //(큐의 첫 번째 요소의 인덱스 - 1)의 값을 가짐
int rear; //(큐의 마지막 요소의 인덱스)의 값을 가짐
element data[MAX_QUEUE_SIZE];
} QueueType;
//오류 함수
void error(char *message) {
fprintf(stderr, "%s\n", message);
exit(1);
}
//큐 초기화 함수
void init_queue(QueueType *q) {
q->rear = -1;
q->front = -1;
}
void queue_print(QueueType *q) {
for (int i = 0; i < MAX_QUEUE_SIZE; i++) {
//큐의 범위에 들지 않은 경우 (전단보다 전이거나 후단보다 후일 경우)
if (i <= q->front || i > q->rear)
printf(" | ");
//큐의 범위 안일 경우
else
printf("%d | ", q->data[i]);
}
printf("\n");
}
//큐가 포화상태인지 검사
int is_full(QueueType *q) {
if (q->rear == MAX_QUEUE_SIZE - 1) //인덱스니까 -1해서 고려
return 1;
else
return 0;
}
//큐가 비어있는 상태인지 검사
int is_empty(QueueType *q) {
if (q->front == q->rear) //전단 == 후단일 경우
return 1;
else
return 0;
}
void enqueue(QueueType *q, int item) {
if (is_full(q)) {
error("큐가 포화상태입니다.");
return;
}
//rear 1 증가하고 data[rear]에 요소 추가
q->data[++(q->rear)] = item;
}
int dequeue(QueueType *q) {
if (is_empty(q)) {
error("큐가 공백상태입니다.");
return -1;
}
//front 1 증가하고 data[front]의 값을 따로 저장해서 리턴
int item = q->data[++(q->front)];
return item;
}
int main(void) {
int item = 0;
QueueType q;
init_queue(&q);
enqueue(&q, 10); queue_print(&q);
enqueue(&q, 20); queue_print(&q);
enqueue(&q, 30); queue_print(&q);
item = dequeue(&q); queue_print(&q);
item = dequeue(&q); queue_print(&q);
item = dequeue(&q); queue_print(&q);
return 0;
}
선형 큐의 문제점 해결.
front와 rear 값이 배열의 끝(MAX_QUEUE_SIZE - 1)에 도달하면 다음 인덱스를 0으로 함. 처음과 끝이 연결되어 있는 형태.
front와 rear의 초기값은 0.
% 연산자를 이용하여 유효 범위를 확인하는게 핵심 코드.
front <- (front + 1) % MAX_QUEUE_SIZE;
rear <- (rear + 1) % MAX_QUEUE_SIZE;
#include <stdio.h>
#include <stdlib.h>
// ===== 원형큐 코드 시작 ======
#define MAX_QUEUE_SIZE 5
typedef int element;
typedef struct {
element data[MAX_QUEUE_SIZE];
int front, rear;
} QueueType;
//오류 함수
void error(char *message) {
fprintf(stderr, "%s\n", message);
exit(1);
}
//front, rear 초기화 함수
void init_queue(QueueType *q) {
q->front = q->rear = 0;
}
//공백 상태 검출 함수
int is_empty(QueueType *q) {
return (q->front == q->rear);
//전단 후단이 같으면 true (공백이다) 반환
}
//포화 상태 검출 함수
int is_full(QueueType *q) {
return ((q->rear + 1) % MAX_QUEUE_SIZE == q->front);
}
//원형큐 출력 함수
void queue_print(QueueType *q) {
printf("QUEUE(front=%d rear=%d) = ", q->front, q->rear);
if (!is_empty(q)) { //비어있지 않은 경우
int i = q->front;
do {
i = (i + 1) % (MAX_QUEUE_SIZE); //원형 큐 인덱스 구하는 식
printf("%d | ", q->data[i]);
if (i == q->rear) //후단에 도달한 경우 멈춤
break;
} while (i != q->front); //다시 원래 자리로 돌아올 때까지 반복
//사실상 위의 if(i == q->rear) break;가 먼저 실행되므로 do-while문의 조건은 부수적인 요소인 셈.
}
printf("\n");
}
//삽입 함수
void enqueue(QueueType *q, element item) {
if (is_full(q))
error("큐가 포화상태입니다");
q->rear = (q->rear + 1) % MAX_QUEUE_SIZE; //원형 큐의 인덱스 계산법
q->data[q->rear] = item; //인덱스 계산 후 요소 삽입
}
//삭제 함수
element dequeue(QueueType *q) {
if (is_empty(q))
error("큐가 공백상태입니다");
q->front = (q->front + 1) % MAX_QUEUE_SIZE; //원형 큐의 인덱스 계산법
return q->data[q->front]; //인덱스 계산 후 해당 요소 반환
}
element peek(QueueType *q) {
if (is_empty(q))
error("큐가 공백상태입니다");
return q->data[(q->front + 1) % MAX_QUEUE_SIZE]; //가장 먼저 삭제될 요소 확인
}
// ====== 원형큐 코드 끝 ======
int main(void) {
QueueType queue;
int element;
init_queue(&queue);
printf("--데이터 추가 단계--\n");
while (!is_full(&queue)) { //큐가 포화 상태가 아닐 경우
printf("정수를 입력하시오 : ");
scanf("%d", &element);
enqueue(&queue, element);
queue_print(&queue);
}
printf("큐는 포화상태입니다.\n\n");
printf("--데이터 삭제 단계--\n");
while (!is_empty(&queue)) { //큐가 비어있지 않을 경우
element = dequeue(&queue);
printf("꺼내진 정수: %d \n", element);
queue_print(&queue);
}
printf("큐는 공백상태입니다.\n");
return 0;
}
QueueType 선언
#define MAX_QUEUE_SIZE 5
typedef int element;
typedef struct {
int front;
int rear;
element data[MAX_QUEUE_SIZE];
} QueueType;
함수 목록
fprintf(stderr, "%s\n", message);
(q->rear + 1) % MAX_QUEUE_SIZE == q->front
코드의 핵심 아이디어
front=0, rear = 1
front=0, rear = 2
front=0, rear = 3
front=1, rear = 3
front=1, rear = 4
버퍼
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_QUEUE_SIZE 5
typedef int element;
typedef struct {
element data[MAX_QUEUE_SIZE];
int front, rear;
} QueueType;
//오류 함수
void error(char *message) {
fprintf(stderr, "%s\n", message);
exit(1);
}
//front, rear 초기화 함수
void init_queue(QueueType *q) {
q->front = q->rear = 0;
}
//공백 상태 검출 함수
int is_empty(QueueType *q) {
return (q->front == q->rear);
//전단 후단이 같으면 true (공백이다) 반환
}
//포화 상태 검출 함수
int is_full(QueueType *q) {
return ((q->rear + 1) % MAX_QUEUE_SIZE == q->front);
}
//원형큐 출력 함수
void queue_print(QueueType *q) {
printf("QUEUE(front=%d rear=%d) = ", q->front, q->rear);
if (!is_empty(q)) { //비어있지 않은 경우
int i = q->front;
do {
i = (i + 1) % (MAX_QUEUE_SIZE); //원형 큐 인덱스 구하는 식
printf("%d | ", q->data[i]);
if (i == q->rear) //후단에 도달한 경우 멈춤
break;
} while (i != q->front); //다시 원래 자리로 돌아올 때까지 반복
//사실상 위의 if(i == q->rear) break;가 먼저 실행되므로 do-while문의 조건은 부수적인 요소인 셈.
}
printf("\n");
}
//삽입 함수
void enqueue(QueueType *q, element item) {
if (is_full(q))
error("큐가 포화상태입니다");
q->rear = (q->rear + 1) % MAX_QUEUE_SIZE; //원형 큐의 인덱스 계산법
q->data[q->rear] = item; //인덱스 계산 후 요소 삽입
}
//삭제 함수
element dequeue(QueueType *q) {
if (is_empty(q))
error("큐가 공백상태입니다");
q->front = (q->front + 1) % MAX_QUEUE_SIZE; //원형 큐의 인덱스 계산법
return q->data[q->front]; //인덱스 계산 후 해당 요소 반환
}
element peek(QueueType *q) {
if (is_empty(q))
error("큐가 공백상태입니다");
return q->data[(q->front + 1) % MAX_QUEUE_SIZE]; //가장 먼저 삭제될 요소 확인
}
int main(void) {
QueueType queue;
int element;
init_queue(&queue);
srand(time(NULL));
//100번 반복하면서 일정한 확률로 원형 큐에 데이터를 삽입하거나 삭제함.
for (int i = 0; i < 100; i++) {
//0부터 RAND_MAX까지의 정수 중 난수 생성
if (rand() % 5 == 0) { //0 1 2 3 4
//20% 확률로 0~99 사이 임의의 정수를 큐에 삽입
enqueue(&queue, rand() % 100);
}
queue_print(&queue);
if (rand() % 10 == 0) { //0 1 2 3 4 5 6 7 8 9
//10% 확률로 큐의 맨 앞의 요소 삭제 후 data에 저장
int data = dequeue(&queue);
}
queue_print(&queue);
}
return 0;
}
Deque (Double-ended Queue)
#include <stdio.h>
#include <stdlib.h>
#define MAX_QUEUE_SIZE 5
typedef int element;
typedef struct {
element data[MAX_QUEUE_SIZE];
int front, rear;
} DequeType;
//오류 함수
void error(char *message) {
fprintf(stderr, "%s\n", message);
exit(1);
}
//초기화
void init_deque(DequeType *q) {
q->front = q->rear = 0;
}
//공백 상태 검출 함수
int is_empty(DequeType *q) {
return (q->front == q->rear);
}
//포화 상태 검출 함수
int is_full(DequeType *q) {
return ((q->rear + 1) % MAX_QUEUE_SIZE == q->front);
}
//원형큐 출력 함수
void deque_print(DequeType *q) {
printf("DEQUE(front=%d rear=%d) = ", q->front, q->rear);
if (!is_empty(q)) {
int i = q->front;
do {
i = (i + 1) % (MAX_QUEUE_SIZE);
printf("%d | ", q->data[i]);
if (i == q->rear)
break;
} while (i != q->front);
}
printf("\n");
}
//삽입 함수
void add_rear(DequeType *q, element item) {
if (is_full(q))
error("큐가 포화상태입니다.");
q->rear = (q->rear + 1) % MAX_QUEUE_SIZE;
q->data[q->rear] = item;
}
//삭제 함수
element delete_front(DequeType *q) {
if (is_empty(q))
error("큐가 공백상태입니다");
q->front = (q->front + 1) % MAX_QUEUE_SIZE;
return q->data[q->front];
}
element get_front(DequeType *q) {
if (is_empty(q))
error("큐가 공백상태입니다");
return q->data[(q->front + 1) % MAX_QUEUE_SIZE];
}
void add_front(DequeType *q, element val) {
if (is_full(q))
error("큐가 포화상태입니다");
q->data[q->front] = val;
q->front = (q->front - 1 + MAX_QUEUE_SIZE) % MAX_QUEUE_SIZE;
}
element delete_rear(DequeType *q) {
int prev = q->rear;
if (is_empty(q))
error("큐가 공백상태입니다");
q->rear = (q->rear - 1 + MAX_QUEUE_SIZE) % MAX_QUEUE_SIZE;
return q->data[prev];
}
element get_rear(DequeType *q) {
if (is_empty(q))
error("큐가 공백상태입니다");
return q->data[q->rear];
}
int main(void) {
DequeType queue;
init_deque(&queue);
for (int i = 0; i < 3; i++) {
add_front(&queue, i);
deque_print(&queue);
}
for (int i = 0; i < 3; i++) {
delete_rear(&queue);
deque_print(&queue);
}
return 0;
}
DequeType 선언
#define MAX_QUEUE_SIZE 5
typedef int element;
typedef struct {
element data[MAX_QUEUE_SIZE];
int front, rear;
} DequeType;
함수 목록
fprintf(stderr, "%s\n", message);
q->front = (q->front - 1 + MAX_QUEUE_SIZE) % MAX_QUEUE_SIZE;
q->rear = (q->rear - 1 + MAX_QUEUE_SIZE) % MAX_QUEUE_SIZE;
예외적으로 add_front와 delete_rear에만 MAX_QUEUE_SIZE를 더하는 구문이 있는데, 이는 인덱스를 감소시킬 때 음수 나머지가 발생하지 않도록 보정하기 위함이다.
헷갈려서 정리
이 시뮬레이션에서 사용할 반복 루프
1. 현재시각 변수 clock +1
2. [0, 10] 사이의 난수 생성
난수 3 새로운 고객 구조체 생성(고객 아이디, 도착시간, 서비스 시간(난수 생성)) enqueue() 호출, 큐에 추가 service_time에 서비스 시간 저장
3. service_time이 0인지 아닌지 검사
service_time != 0 어떤 고객이 서비스를 받고 있는 중
clock + 1 service_time - 1
service_time == 0 서비스 받는 고객이 없음 큐에서 고객 구조체 꺼내고 서비스 시작 service_time에 서비스 시간 저장
4. 60분 지나면 고객들이 기다린 시간을 전부 합하여 출력.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_QUEUE_SIZE 5
typedef struct {
int id;
int arrival_time;
int service_time;
} element;
typedef struct {
element data[MAX_QUEUE_SIZE];
int front, rear;
} QueueType;
//오류 함수
void error(char *message) {
fprintf(stderr, "%s\n", message);
exit(1);
}
//front, rear 초기화 함수
void init_queue(QueueType *q) {
q->front = q->rear = 0;
}
//공백 상태 검출 함수
int is_empty(QueueType *q) {
return (q->front == q->rear);
//전단 후단이 같으면 true (공백이다) 반환
}
//포화 상태 검출 함수
int is_full(QueueType *q) {
return ((q->rear + 1) % MAX_QUEUE_SIZE == q->front);
}
//원형큐 출력 함수
void queue_print(QueueType *q) {
printf("QUEUE(front=%d rear=%d) = ", q->front, q->rear);
if (!is_empty(q)) { //비어있지 않은 경우
int i = q->front;
do {
i = (i + 1) % (MAX_QUEUE_SIZE); //원형 큐 인덱스 구하는 식
printf("%d | ", q->data[i]);
if (i == q->rear) //후단에 도달한 경우 멈춤
break;
} while (i != q->front); //다시 원래 자리로 돌아올 때까지 반복
//사실상 위의 if(i == q->rear) break;가 먼저 실행되므로 do-while문의 조건은 부수적인 요소인 셈.
}
printf("\n");
}
//삽입 함수
void enqueue(QueueType *q, element item) {
if (is_full(q))
error("큐가 포화상태입니다");
q->rear = (q->rear + 1) % MAX_QUEUE_SIZE; //원형 큐의 인덱스 계산법
q->data[q->rear] = item; //인덱스 계산 후 요소 삽입
}
//삭제 함수
element dequeue(QueueType *q) {
if (is_empty(q))
error("큐가 공백상태입니다");
q->front = (q->front + 1) % MAX_QUEUE_SIZE; //원형 큐의 인덱스 계산법
return q->data[q->front]; //인덱스 계산 후 해당 요소 반환
}
element peek(QueueType *q) {
if (is_empty(q))
error("큐가 공백상태입니다");
return q->data[(q->front + 1) % MAX_QUEUE_SIZE]; //가장 먼저 삭제될 요소 확인
}
int main(void) {
int minutes = 60;
int total_wait = 0;
int total_customers = 0;
int service_time = 0;
int service_customer;
QueueType queue;
init_queue(&queue);
srand(time(NULL));
for (int clock = 0; clock < minutes; clock++) { //60분 동안
printf("현재시각=%d\n", clock);
if ((rand() % 10) < 3) { //0~9 난수 생성 후 3보다 작을 경우
element customer;
customer.id = total_customers++;
//total_customer를 id에 저장 후 +1
customer.arrival_time = clock;
//customer_id 생성 후의 시간 = arrival time
customer.service_time = rand() % 3 + 1;
//1~3 난수 생성 -> 서비스 시간
enqueue(&queue, customer);
printf("고객 %d이 %d분에 들어옵니다. 업무처리시간= %d분\n",
customer.id, customer.arrival_time, customer.service_time);
}
if (service_time > 0) { //잔여 서비스 시간이 있을 경우
printf("고객 %d 업무처리중입니다. \n", service_customer);
service_time--;
}
else { //서비스 시간이 끝난 경우
if (!is_empty(&queue)) { //큐가 비어있지 않은 경우
element customer = dequeue(&queue);
service_customer = customer.id;
service_time = customer.service_time;
printf("고객 %d이 %d분에 업무를 시작합니다. 대기시간은 %d분이었습니다. \n",
customer.id, clock, clock - customer.arrival_time);
total_wait += clock - customer.arrival_time;
}
}
}
printf("전체 대기 시간=%d분 \n", total_wait);
return 0;
}
element, QueueType 선언
typedef struct {
int id; //고객 아이디
int arrival_time; //도착시간
int service_time; //서비스 시간 (난수)
} element;
typedef struct {
element data[MAX_QUEUE_SIZE];
int front, rear;
} QueueType;
함수 목록
fprintf(stderr, "%s\n", message);
위 코드에서는 은행원이 1명이라고 가정한다. 만약 은행원이 2명이라면 어떻게 수정해야 하는가?
각 은행원의 잔여 서비스 시간과 처리 중인 고객을 별도로 관리해야 한다. service_time과 service_customer를 크기가 2인 배열로 변경하고 반복문을 통해 은행원 2명이 각각 대기 큐에서 고객을 꺼내 업무를 처리하도록 수정한다.