// 큐는 선입선출 방식이다.

먼저 들어가면 먼저 나옴.



main.c


#include <stdio.h>

#include "queue.h"


int main(){


struct data q;


init(&q);


enqueue(&q, 1);

enqueue(&q, 2);

enqueue(&q, 3);

enqueue(&q, 4);


while (!empty(&q)){

printf("%d ", dequeue(&q));

}


return 0;

}



queue.c (정의문)



#include <stdio.h>

#include <stdlib.h>

#include "queue.h"


void init(struct data *a){


a->front = 0;  // front와 rear은 0에서 초기화된다.

a->rear = 0;

}


int empty(struct data *a){  


if (a->front == a->rear){  // // 배열이 비어있다면 1을 반환한다.

return 1;  // front와 rear이 같다는 것은 비어있다는 것을 의미함.

}

else{

return 0;

}

}


int nextpos(int num){ 


if (num == 100 - 1){  // 배열의 마지막 인덱스와 같은가?

return 0;  // 그럼 0을 반환

}

else{  // 배열이 가득차지 않았다면 인덱스를 1 증가시킨다.

return num + 1;

}

}


void enqueue(struct data *a, int num){


if (nextpos(a->rear) == a->front){  // 배열에 넣기전에 먼저 가득차있는지 검사한다.

exit(-1);

}


a->rear = nextpos(a->rear);  // 증가된 인덱스를 rear에 넣는다.

a->arr[a->rear] = num;  // 배열에 값을 넣음

}


int dequeue(struct data *a){


if (empty(a)){  // 배열이 비어있는가?

exit(-1);

}


a->front = nextpos(a->front);  // 증가된 인덱스를 front에 넣는다.

return a->arr[a->front];  // 반환해서 printf로 찍어준다.

}





queue.h (선언문)


struct data{

int front;  //  출력시 인덱스 움직임

int rear;  // 입력시 인덱스 움직임


int arr[100];

};


void init(struct data *a);

int empty(struct data *a);

void enqueue(struct data *a, int num);

int dequeue(struct data *a);




// 저장할땐 rear을 움직여 저장하고 출력할 땐 front를 움직이며 출력한다.

// 출력 1 2 3 4 

 

'자료구조' 카테고리의 다른 글

[자료구조] 퀵소트  (0) 2019.12.12
[자료구조] 리스트로 된 큐  (0) 2019.12.12
[자료구조] 리스트로 된 스택  (0) 2019.12.12
[자료구조] 배열로 된 스택  (0) 2019.12.12
[자료구조] 링크드 리스트의 이해  (0) 2019.12.12
블로그 이미지

ryancha9

https://blog.naver.com/7246lsy

,