June is Combung

Queue 본문

C 자료구조와 알고리즘

Queue

june__Park 2021. 6. 29. 19:00
#include <stdio.h>
#include <Windows.h>
/*
	< QUEUE 구조 >
	- 선입선출
	- FIFO (First In First Out) 
	- head(=front) : 가장 앞 노드를 가리킴
	  tail(=rear)  : 가장 마지막 노드를 가리킴 

	- enqueue : 데이터 추가 
		=> tail 이 변경됨 
		=> 최초 노드 생성일 때만 head 가 1회 변경됨 
	  dequeue : 데이터 처리(삭제)
		=> head 가 변경됨 
		=> 마지막 노드 삭제 tail 이 1회 변경됨 (NULL로)
*/

#define MAX 5
int arr[MAX] = {0};
int head = -1;
int tail = -1;
void enqueue(int data){
	//	=> tail 이 변경됨 
	//	=> 최초 노드 생성일 때만 head 가 1회 변경됨 
	if( (tail + 1) % MAX == head ){
		printf("Queue Overflow! \n");
		return;
	}
	//tail = (tail + 1) % MAX;
	//arr[tail] = data;
	arr[++tail %= MAX] = data;
	/*if (head == -1){
		head = tail;
	}*/
}
void dequeue(){
	//	=> head 가 변경됨 
	//	=> 마지막 노드 삭제 tail 이 1회 변경됨 (NULL로)
	if(head == -1){
		printf("Queue Underflow! \n");
		return;
	}
	
	arr[head] = 0;

	if(head == tail){  // 노드 1개뿐?
		head = tail = -1;
		return;
	}
	head = (head+1) % MAX;	
}
void peek(){
	if(tail == -1){
		printf("원소가 없습니다. \n");
		return;
	}
	printf("현재 dequeue 할 데이터는 %d 입니다. \n", arr[tail]);
}
void print_all(){
	int front = head;
	int rear = tail;

	printf("h:%d t:%d \n", head, tail);

	if (front == -1){
		printf("[원소 없음] \n");
		return;
	}
	while(front != rear) {
		printf("%d ", arr[front]);
		front = (front + 1) % 5;
	} 
	printf("%d \n", arr[front]);
}
void main(){
	int data;
	int select;
	while(1){
		print_all();
		printf("1. enqueue \n2. dequeue \n3. peek \n4. exit \n입력 : ");
		scanf_s("%d", &select);
		switch(select){
		case 1:
			printf("추가할 정수 : "); scanf_s("%d", &data);
			enqueue(data);
			break;
		case 2:
			dequeue();
			break;
		case 3:
			peek();
			break;
		case 4:
			return;
		} // switch 
		system("pause");
		system("cls");
	} // while 
}

'C 자료구조와 알고리즘' 카테고리의 다른 글

이중 연결리스트  (0) 2021.06.29
단일 연결리스트  (0) 2021.06.29
연습문제1  (0) 2021.06.29
연결리스트(중간 노드 삽입 삭제) 이중포인터 버전  (0) 2021.06.29
Queue 연결리스트  (0) 2021.06.29
Comments