상세 컨텐츠

본문 제목

선형큐

Coding/자료구조(with C)

by 세미531 2021. 10. 17. 14:11

본문

728x90

큐도 스택과 마찬가지로 구현하는 방법이 여러 가지이나 1차원 배열을 쓰는 방법을 먼저 알아보자. 정수를 저장할 수 있는 큐를 만들어 보면 먼저 정수의 1차원 배열을 정의하고 삽입, 삭제를 위한 변수 front 와 rear 를 만든다. front 는 큐의 첫 번째 요소를 가리키고 rear 는 큐의 마지막 요소를 가리킨다.

#include <stdio.h>
#include <stdlib.h>
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable:4996)
#include <malloc.h>
#include <string.h>

#define MAX_QUEUE_SIZE 5

typedef int element;
typedef struct {
  int front;
  int rear;
  element data[MAX_QUEUE_SIZE];
} QueueType;

//오류 함수
void error(char*message)
{
  fprintf(stderr,"%s\n",message);
  exit(1);
}

void init_queue(QueueType *q) {
  q->rear = -1;
  q->front = -1;
}

void queue_print(QueueType *q)
{
  for (int i = 0; i < MAX_QUEUE_SIZE; i++) {
    if (i <= q->front || i > q->rear)
      printf(" | ");
    else printf("%d | ",q->data[i]);
  }
  printf("\n");
}

int is_full(QueueType *q)
{
  if (q->rear == MAX_QUEUE_SIZE - 1)
    return 1;
  else
    return 0;
}

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

void enqueue(QueueType *q, int item)
{
  if (is_full(q)) {
    error("큐가 포화상태입니다");
    return;
  }
  q->data[++(q->rear)] = item;
}

/*void아님*/int dequeue(QueueType *q)
{
  if (is_empty(q)) {
    error("큐가 공백상태입니다");
    return -1;
  }
  int item = q->data[++(q->front)];
  return item;
}

int main()
{
  int item = 0;
  QueueType q;

  init_queue(&q);

  enqueue(&q,10); queue_print(&q);
  enqueue(&q,20); queue_print(&q);
  enqueue(&q,30); queue_print(&q);

  item = dequeue(&q); queue_print(&q);
  item = dequeue(&q); queue_print(&q);
  item = dequeue(&q); queue_print(&q);
  return 0;
}

 

 

728x90

'Coding > 자료구조(with C)' 카테고리의 다른 글

원형큐의 구현  (0) 2021.10.17
원형큐  (0) 2021.10.17
동적 배열 스택  (0) 2021.10.17
관련된 데이터를 함수의 매개변수로 전달하는 방법  (0) 2021.10.17
스택의 요소를 구조체로 하기  (0) 2021.10.17

관련글 더보기

댓글 영역