C언어 큐에 대해 질문드립니다.(enqueue)
조회수 1008회
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
#define DataType char
typedef struct ArrayQueue {
int front;
int rear;
DataType queue[MAX_SIZE];
} ArrayQueue;
void init_queue(ArrayQueue *AQ){ // 큐 초기화
AQ->front = AQ->rear = 0;
}
int is_queue_full(ArrayQueue *AQ){ // 큐가 포화상태인지 판단
return ((AQ->rear + 1) % MAX_SIZE) == AQ->front;
}
int is_queue_empty(ArrayQueue *AQ){ // 큐가 공백상태인지 판단
return AQ->front == AQ->rear;
}
void enqueue(ArrayQueue *AQ, DataType data){ // 큐에 삽입
if (is_queue_full(AQ)){
printf("삽입 불가\n");
exit(1);
}
else {
int len = strlen(data);
AQ->rear = (AQ->rear + len) % MAX_SIZE;
AQ->queue[AQ->rear] = data;
}
}
void print_queue(ArrayQueue *AQ){ // 큐 항목들을 출력
printf("front->");
int i;
for(i = AQ->front; i != AQ->rear; ){
i = (i+1) % MAX_SIZE;
printf("%d ", AQ->queue[i]);
}
printf("\n");
}
main(){
ArrayQueue male, female;
init_queue(&male);
init_queue(&female);
char name[MAX_SIZE];
char gender;
printf("고객이름 : ");
scanf("%s", name);
printf("셩별을 입력하세요(f or m) : ");
scanf(" %c", &gender);
if(strcmp(gender, 'm'))
enqueue(&male, name);
else if(strcmp(gender, 'f'))
enqueue(&female, name);
print_queue(&male);
}
과제 중에 벽에 부딪혀 질문드립니다. 고객의 이름과 성별을 입력받아 성별이 남자(m)면 male이라는 큐에, 여자(f)면 female이라는 큐에 각각 이름을 저장하고 싶습니다.
코드를 작성 후 시험삼아 고객 이름 "홍길동", 성별 "m"을 입력 후 저장된 큐 male을 print_queue를 이용해 출력해 보았는데 출력이 되지 않았습니다.
enqueue 부분에서 문제가 생긴 것 같습니다. 우선 len이라는 정수 변수를 선언후 strlen을 이용해 data(이름)의 길이를 저장 후 rear를 len을 이용해 이동 후 data를 입력하였습니다.
int len = strlen(data);
AQ->rear = (AQ->rear + len) % MAX_SIZE;
AQ->queue[AQ->rear] = data;
제가 생각하는 문제점은 AQ->queue[AQ->rear] = data; 이 부분에서 입력한 데이터의 위치를 AQ->queue[AQ->rear]로 잡으면 입력한 data는 문자열이기 때문에 단일 위치인 AQ->queue[AQ->rear]에 저장되지 않는다였습니다.
그렇기 때문에 enqueue부분의 코드도
AQ->rear = (AQ->rear + 1) % MAX_SIZE;
AQ->queue[AQ->rear] = data;
로 바꿔보고 이름을 단일 문자로 입력해보았지만 결과는 마찬가지였습니다.
해당 코드에 어떤 문제가 있는것인지 알고 싶습니다.
댓글 입력