큐는 자료를 한쪽으로 보관하고 다른쪽에서 꺼내는 FIFO(First In First Out) 방식의 자료구조입니다. 큐에 자료를 보관하는 연산을 PUT 혹은 ENQUEUE라 말하고 꺼내는 연산을 GET 혹은 DEQUEUE라고 말합니다. 그리고 보관할 위치 정보를 rear, 꺼낼 위치 정보를 front라고 말해요.
연결리스트를 이용하여 구현한 큐에서는 보관할 때 rear 뒤에 보관하고 꺼낼 때 front에 있는 것을 꺼냅니다. 그리고 보관할 때 허용하는 메모리 범위 내에서 보관할 수 있어 꽉 찼는지 확인할 필요가 없습니다.
알고리즘
PUT 연산 now = MakeNode(data) (노드생성)
IF Queue Is Empty (비어있을때) front = now (front를 now로설정) Else (비어있지않을때)
rear의 next= now (rear의 netx를 now로설정) rear=now (rear를 now로설정)
GET 연산 IF Queue is empty Then (비었으면) Underflow (버퍼언더플로우) Else now = front
data = front의 data (data를 front의 data로설정)
fornt =now의 next (front를 now의 next로설정)
DisposeNode(now) (now 노드소멸)
data 반환
원형 큐 실행 화면
소스 코드
C
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
//큐 - 연결리스트 이용
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedefstructNode//노드 정의
{
intdata;
structNode*next;
}Node;
typedefstructQueue//Queue 구조체 정의
{
Node*front;//맨 앞(꺼낼 위치)
Node*rear;//맨 뒤(보관할 위치)
intcount;//보관 개수
}Queue;
voidInitQueue(Queue*queue);//큐 초기화
intIsEmpty(Queue*queue);//큐가 비었는지 확인
voidEnqueue(Queue*queue,intdata);//큐에 보관
intDequeue(Queue*queue);//큐에서 꺼냄
intmain(void)
{
inti;
Queue queue;
InitQueue(&queue);//큐 초기화
for(i=1;i<=5;i++)//1~5까지 큐에 보관
{
Enqueue(&queue,i);
}
while(!IsEmpty(&queue))//큐가 비어있지 않다면 반복
{
printf("%d ",Dequeue(&queue));//큐에서 꺼내온 값 출력
}
printf("\n");
return0;
}
voidInitQueue(Queue*queue)
{
queue->front=queue->rear=NULL;//front와 rear를 NULL로 설정