1 분 소요

Queue

이번 목표는 자료구조중 하나인 Queue를 c 언어로 구현하는 것 이다. Queue의 경우 Stack이랑 다르게 선입 선출(FIFO, First in First Out)을 사용한다. 대기줄이라고 생각을 하면 편하다.

기능

큐에 기본 기능들은 init, push, pop, size, empty, front, back이다.

init -> 큐 초기화

push -> 데이터를 가장 뒤에 삽입

pop -> 가장 앞 데이터 추출

size -> 큐 크기 확인

empty -> 큐가 비어있는지 유무 확인

front -> 가장 앞에 데이터 확인

back -> 가장 뒤에 있는 데이터 확인

구현

#include <stdio.h>

typedef struct {
	int arr[10000];
	int front;
	int back;
}Queue;

int init(Queue *q)
{
	q->front=0;	
	q->back=0;
}

void push(Queue *q, int num)
{
	q->arr[q->back++] = num;
	
}

int pop(Queue *q)
{
	if(empty(q)==1)
	{
		printf("pop\nqueue is empty\n________\n");
		return -1;
	}
	printf("pop\n %d\n________\n",q->arr[q->front]);
	return q->arr[q->front++];
}

int size(Queue *q)
{
	printf("size\nsize is %d\n________\n",q->back - q->front);
	return q->back - q->front;
}

int empty(Queue *q)
{
	if(q->front==q->back)
	{
		printf("empty\nqueue is empty\n_______\n");
		return 1;
	}
	printf("empty\nqueue is not empty\n______\n");
	return 0;
}

int front(Queue *q)
{
	if(empty(q)==1)
	{
		printf("front\nqueue is empty\n________\n");
		return -1;
	}
	printf("front\n %d\n________\n",q->arr[q->front]);
	return q->arr[q->front];
}

int back(Queue *q)
{
	if(empty(q)==1)
	{
		printf("back\nqueue is empty\n________\n");
		return -1;
	}
	printf("back\n %d\n________\n",q->arr[q->back -1]);
	return q->arr[q->back-1];
}


int main()
{
	Queue q;
	init(&q);
	push(&q,2);
	push(&q,4);
	push(&q,6);
	pop(&q);
	size(&q);
	empty(&q);
	back(&q);
	front(&q);
	pop(&q);
	pop(&q);
	pop(&q);
	
	return 0;
}

결과

pop
 2
________
size
size is 2
________
empty
queue is not empty
______
back
 6
________
front
 4
________
pop
 4
________
pop
 6
________
pop
queue is empty
________

댓글남기기