연재 완료/C Lang 예제코드 모음

C언어 구조체 및 공용체 주요예제3 (queue구현)

라이피 (Lypi) 2018. 5. 28. 23:29
반응형

내용 출처 : YES C (정보공학연구소 /생능출판사)



단순 연결 리스트를 이용하여 생성한 큐(queue)를 이용하는 프로그램

// A linked list implementation of a queue.

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <ctype.h>

#define EMPTY	0
#define FULL	10000

typedef unsigned int data;

struct element{
	data	 d;
	element* next;
};
//an element in the queue


struct queue {
	int cnt;			//a count of the elements
	element* front;		//ptr to the front element
	element* rear;		//ptr to the rear element
};

void initialize(queue *q);
data dequeue(queue *q);
void enqueue(data d, queue *q);
data front(const queue *q);
bool empty(const queue *q);
bool full(const queue *q);


//using queues to schedule two resources.
int main() 
{
	int c;
	int cnt_a = 0;
	int cnt_b = 0;
	data pid;
	queue a, b;

	initialize(&a);
	initialize(&b);

	//enqueue the requests.

	while ((c = getchar()) != EOF) {
		switch (toupper(c)) {
		case 'A':
			assert(scanf_s("%u", &pid) == 1);
			if (!full(&a)) {
				enqueue(pid, &a);
			}
			break;
			
		case 'B':
			assert(scanf_s("%u", &pid) == 1);
			if (!full(&b)) {
				enqueue(pid, &b);
			}
		}
	}

	//Dequeue the requests and print them.

	printf("---\n");
	printf("A's schedule : \n");

	while (!empty(&a)) {
		pid = dequeue(&a);
		printf("JOB %u is %d \n", ++cnt_a, pid);
	}
	printf("\n");

	printf("---\n");
	printf("B's schedule : \n");

	while (!empty(&b)) {
		pid = dequeue(&b);
		printf("JOB %u is %d \n", ++cnt_b, pid);
	}
	printf("\n");

	return 0;

}

//the basic queue routines
void	initialize(queue *q) 
{
	q->cnt = 0;
	q->front = NULL;
	q->rear = NULL;
}

data dequeue(queue *q) 
{
	data d;
	element *p;

	d = q->front->d;
	p = q->front;
	q->front = q->front->next;
	q->cnt--;

	free(p);
	return d;
}

void enqueue(data d, queue *q)
{
	element* p;

	p = (element*)malloc(sizeof(element));
	p->d = d;
	p->next = NULL;
	if (!empty(q)) {
		q->rear->next = p;
		q->rear = p;
	}
	else {
		q->front = q->rear = p;
	}

	q->cnt++;
}

data front(const queue *q)
{
	return q->front->d;
}

bool empty(const queue *q)
{
	return (bool)(q->cnt == EMPTY);
}

bool full(const queue *q)
{
	return (bool)(q->cnt == FULL);
}



반응형