Skip to content

Instantly share code, notes, and snippets.

@Kinetic27
Created March 16, 2022 08:21
Show Gist options
  • Save Kinetic27/86b2445b504aa474fb3e8a766c9aaf76 to your computer and use it in GitHub Desktop.
Save Kinetic27/86b2445b504aa474fb3e8a766c9aaf76 to your computer and use it in GitHub Desktop.
링 버퍼 구현 과제 1
#include <stdio.h>
#define MAX_SIZE 5
// global variables
int queue[MAX_SIZE];
int front = 0;
int rear = 0;
// check if queue is full
int queue_full()
{
// return 0 only if the above condition is false
return (front == 1 && rear == MAX_SIZE) || front == rear + 1;
}
// check if queue is empty
int queue_empty()
{
// return 0 only if the above condition is false
return front == 0;
}
// add an element to the queue
void enqueue(int x)
{
// check if queue is full
if (queue_full())
{
printf("Queue is overflow, ");
return;
}
if (rear == MAX_SIZE)
rear = 1;
else if (front == 0 && rear == 0)
{
front = 1;
rear++;
}
else
rear++;
queue[rear] = x;
}
// remove an element from the queue
int dequeue()
{
// check if queue is empty
if (queue_empty())
{
printf("Queue is underflow, ");
return -1;
}
int temp = queue[front];
if (front == MAX_SIZE)
front = 1;
else if (front == rear)
{
front = 0;
rear = 0;
}
else
front++;
return temp;
}
// helper function: print the current queue
void print_queue()
{
int front_pos = front, rear_pos = rear;
printf("queue =");
// if queue is empty
if (!queue_empty())
{
// normal case of queue
if (front_pos <= rear_pos) {
while (front_pos <= rear_pos)
{
printf(" %d", queue[front_pos]);
front_pos++;
}
}
else
{
// special case of queue (front_pos > rear_pos)
while (front_pos <= MAX_SIZE)
{
printf(" %d", queue[front_pos]);
front_pos++;
}
front_pos = 1;
while (front_pos <= rear_pos)
{
printf(" %d", queue[front_pos]);
front_pos++;
}
}
}
// print front and rear
printf(" (rear=%d, front=%d)\n", rear, front);
}
int main()
{
int insert_test[] = { 10, 50, 20, 70 };
for (int i = 0; i < 4; i++)
{
printf("enqueue(%d), ", insert_test[i]);
enqueue(insert_test[i]);
print_queue();
}
printf("dequeue() = %d, ", dequeue());
print_queue();
int insert_test2[] = { 100, 40, 140, 70 };
for (int i = 0; i < 3; i++)
{
printf("enqueue(%d), ", insert_test2[i]);
enqueue(insert_test2[i]);
print_queue();
}
for (int i = 0; i < 3; i++)
{
printf("dequeue() = %d, ", dequeue());
print_queue();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment