Data Structure – Queue 피보나치 수열

Fibonacci Sequence Source

#include <stdio.h>
#define MAX_QUEUE_SIZE 5
typedef int element;
typedef struct {
	element data[MAX_QUEUE_SIZE];
	int front, rear;
}QueueType;
typedef QueueType * QueueType_ptr;

QueueType q;

void init(QueueType_ptr q) {
	q->front = 0;
	q->rear = 0;
}

int is_empty(QueueType q) {
	if (q.front == q.rear)
		return 1;
	else
		return 0;
};

int is_full(QueueType q) {
	if ((q.rear + 1) % MAX_QUEUE_SIZE == q.front)
		return 1;
	else
		return 0;
}

void enqueue(QueueType_ptr q, int item) {
	if (!is_full(*q)) {
		q->rear = (q->rear + 1) % 5;
		q->data[q->rear] = item;
	}
	else
		printf("큐가 꽉 찼습니다");
}

int dequeue(QueueType_ptr q) {
	if (!is_empty(*q)) {
		q->front = (q->front + 1) % 5;
		return q->data[q->front];
	}
	else
		printf("큐가 비어 있습니다");
}

int peek(QueueType q) {
	if (!is_empty(q)) 
		return q.data[(q.front+1)%MAX_QUEUE_SIZE];
	else
		printf("큐가 비어 있습니다");
}


int F(int n) {
	if (n == 0)
		return 0;
	else if (n == 1)
		return 1;
	else {
		int first, second; //첫 번째 요소, 두 번째 요소 
		enqueue(&q, 0);
		enqueue(&q, 1);
		for (int i = 1; i < n; i++) {
			first = dequeue(&q); // 첫 번째 요소
			second = peek(q);
			enqueue(&q, first + second); 
		}
		dequeue(&q); 
		return 	dequeue(&q);
	}

}

int main(void) {
	init(&q);
	for (int i = 0; i < 20; i++)
		printf("%d ", F(i));
	system("pause");
}

Leave a Reply

Your email address will not be published. Required fields are marked *