ํ(Queue)๋? ๋ค์ชฝ์ผ๋ก ๋ค์ด๊ฐ์ ์์ชฝ์ผ๋ก ๋์ค๋(์ ์ ์ ์ถ) ์๋ฃ ๊ตฌ์กฐ ํํ.
1) ๋ค์ชฝ์ผ๋ก ๋ค์ด๊ฐ์ ์์ชฝ์ผ๋ก ๋์ค๋(์ ์
์ ์ถ) ์๋ฃ ๊ตฌ์กฐ ํํ.
2) ์ค์ผ์ค๋ง, ํ์ ์๊ณ ๋ฆฌ์ฆ ๋ฑ์์ ๋ค๋ฐฉ๋ฉด์ผ๋ก ํ์ฉ๋จ
PUSH
: ํ์ ๋ฐ์ดํฐ ์ถ๊ฐPOP
: ํ์์ ๋ฐ์ดํฐ ์ญ์ 3) ์์: PUSH(7) โ PUSH(5) โ PUSH(4) โ POP() โ PUSH(6) โ POP()
1) ํ(Queue)์ ๊ตฌํ ๋ฐฉ๋ฒ์๋
2) ๊ฐ์ฅ ๊ธฐ๋ณธ์ ์ธ ํํ์ ์๋ฃ๊ตฌ์กฐ๋ก ๊ตฌํ ๋์ด๋๋ ๋ฎ์ ํธ
1) ํ์ ์ ์ธ
#include <stdio.h>
#define SIZE 10000
#define INF 99999999
int queue[SIZE];
int front = 0;
int rear = 0;
2) ํ ์ฝ์ ํจ์
void push(int data) {
if (rear >= SIZE) {
printf("ํ ์ค๋ฒํ๋ก์ฐ๊ฐ ๋ฐ์ํ์ต๋๋ค.\n");
return; }
queue[rear++] = data;
}
3) ํ ์ถ์ถ ํจ์
int pop() {
if (front == rear) {
printf("ํ ์ธ๋ํ๋ก์ฐ๊ฐ ๋ฐ์ํ์ต๋๋ค.\n");
return -INF;
}
return queue[front++];
}
4) ํ ์ ์ฒด์ถ๋ ฅ ํจ์
void show() {
printf("--- ํ์ ์ ---\n");
for (int i = front; i < rear; i++) {
printf("%d\n", queue[i]);
}
printf("--- ํ์ ๋ค ---\n");
}
5) ์์ฑ๋ ํ ์ฌ์ฉํ๊ธฐ
int main(void) {
push(7);
push(5);
push(4);
pop();
push(6);
pop();
show();
system("pause");
return 0;
}
1) ํ์ ์ ์ธ
#include <stdio.h>
#include <stdlib.h>
#define INF 99999999
typedef struct {
int data;
struct Node *next;
} Node;
typedef struct {
Node *front;
Node *rear;
int count;
} Queue;
2) ํ ์ฝ์ ํจ์
void push(Queue *queue, int data) {
Node *node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = NULL;
if (queue->count == 0) {
queue->front = node;
} else {
queue->rear->next = node;
}
queue->rear = node;
queue->count++;
}
3) ํ ์ถ์ถ ํจ์
int pop(Queue *queue) {
if (queue->count == 0) {
printf("ํ ์ธ๋ํ๋ก์ฐ๊ฐ ๋ฐ์ํ์ต๋๋ค.\n");
return -INF;
}
Node *node = queue->front;
int data = node->data;
queue->front = node->next;
free(node);
queue->count--;
return data;
}
4) ํ ์ ์ฒด์ถ๋ ฅ ํจ์
void show(Queue *queue) {
Node *cur = queue->front;
printf("--- ํ์ ์ ---\n");
while (cur != NULL) {
printf("%d\n", cur->data);
cur = cur->next;
}
printf("--- ํ์ ๋ค ---\n");
}
5) ์์ฑ๋ ํ ์ฌ์ฉํ๊ธฐ
int main(void) {
Queue queue;
queue.front = queue.rear = NULL;
queue.count = 0;
push(&queue, 7);
push(&queue, 5);
push(&queue, 4);
pop(&queue);
push(&queue, 6);
pop(&queue);
show(&queue);
system("pause");
return 0;
}