[Data Structure] 큐 Queue

KingU·2021년 12월 9일
0

Data Structure

목록 보기
4/5
post-thumbnail

🌟 큐 Queue



사전적 의미:

줄(무엇을 기다리는 사람, 자동차 등), 줄을 서서 기다리는 것



특징:

  • 선입선출 First In First Out

  • 큐는 한쪽 끝에서 작업이 이루어지고 다른 쪽에서 삭제 작업이 이뤄짐



상태:

인큐 enQueue

디큐 dnQueue

공백상태 empty

포화상태 full



위치:

삭제 위치 front

삽입 위치 rear






사용법 📚


#include <stdio.h>
#include <stdlib.h>
typedef int ELEMENT ;
typedef struct queue{
	ELEMENT * buf;
	int front;
	int rear;
	int size;
}QUEUE;	// QUEUE라는 구조체 정의
QUEUE * createQueue( int n );
int isFull( QUEUE *q );
void enQueue( QUEUE *q, ELEMENT data );
int isEmpty( QUEUE *q );
ELEMENT deQueue( QUEUE *q );
void destroyQueue( QUEUE * q );
void printAll( QUEUE *q );
int main() {
	QUEUE *q;
	ELEMENT data, result;
	int n;
	scanf("%d", &n);
	q = createQueue(n);
	for(int i=0; i<n; i++){
		enQueue(q, i+1);
	}
	for(int i=0; i<n-1; i++){
	deQueue(q);
	int m = deQueue(q);
	enQueue(q, m);
	}
	printAll(q);
	
	destroyQueue( q );
	return 0;
}
QUEUE * createQueue( int n ){
	QUEUE *temp = (QUEUE *) malloc( sizeof(QUEUE) );
	temp -> size = n+1;
	temp -> rear = 0;
	temp -> front = 0;
	temp -> buf = (ELEMENT *)malloc(sizeof(ELEMENT)*temp->size);
	return temp;
}
int isFull( QUEUE *q ){
	return (q->rear + 1) % q->size == q->front ;	// true return
}
void enQueue( QUEUE *q, ELEMENT data ){
	if( isFull( q ) ) printf("Queue is full\n");
	else {
		q -> rear = ( q->rear + 1 ) % q->size; 
		q->buf[ q->rear ] = data;
	}
}
int isEmpty( QUEUE *q ){
	return q->rear == q->front;
}
ELEMENT deQueue( QUEUE *q ){
	if( isEmpty( q ) ){
		printf("Queue is empty");
		return 0;
	}
	q->front = ( q->front + 1 ) % q->size ;
	return q->buf[ q->front ];
}
void destroyQueue( QUEUE * q ){
	free( q->buf );
	free( q );
}

void printAll( QUEUE *q ){
	int i;
	int end = (q->front < q->rear)? q->rear : q->rear + q->size;
	if( isEmpty(q)) return;
	for( i = q->front+1 ; i <= end ; i++ ){
		printf("%d ", q->buf[i%(q->size)] );	
	} 
	printf("\n");
}




당신의 시간이 헛되지 않는 글이 되겠습니다.
I'll write something that won't waste your time.

profile
원하는 것을 창조하고 창조한 것을 의미있게 사용하자

0개의 댓글

관련 채용 정보