컴공 일기122
게시글 주소: https://orbi.kr/00057534660
백준 문제 풀고 있는데 링크드 큐를 이용한 응용 문제입니다. 소스코드는 대충 이렇습니다.
에러는 안 뜹니다만, 문제 조건을 조금 더 맞추어야 하기 때문에 여기서 수정을 조금 더 해야할 듯 싶습니다.
scanf는 버퍼함수라는 것을 다시한번...
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct tagNode
{
int Data;
struct tagNode* NextNode;
}Node;
typedef struct tagLinkedQueue
{
Node* Front;
Node* Rear;
int Count;
}LinkedQueue;
void LQ_CreateQueue(LinkedQueue** Queue)
{
(*Queue) = (LinkedQueue*)malloc(sizeof(LinkedQueue));
(*Queue)->Front = NULL;
(*Queue)->Rear = NULL;
(*Queue)->Count = 0;
}
Node* LQ_CreateNode(int Data)
{
Node* NewNode = (Node*)malloc(sizeof(Node));
NewNode->Data = Data;
NewNode->NextNode = NULL;
return NewNode;
}
void LQ_Enqueue(LinkedQueue* Queue, Node* NewNode)
{
if (Queue->Front == NULL)
{
Queue->Front = NewNode;
Queue->Rear = NewNode;
Queue->Count++;
}
else
{
Queue->Rear->NextNode = NewNode;
Queue->Rear = NewNode;
Queue->Count++;
}
}
Node* LQ_Dequeue(LinkedQueue* Queue)
{
Node* Front = Queue->Front;
if (Queue->Front->NextNode == NULL)
{
Queue->Front = NULL;
Queue->Rear = NULL;
}
else
{
Queue->Front = Queue->Front->NextNode;
}
Queue->Count--;
return Front;
}
int LQ_IsEmpty(LinkedQueue* Queue)
{
return (Queue->Front == NULL);
}
int frontPrint(LinkedQueue* Queue)
{
if (Queue->Count == 0)
{
return -1;
}
else
printf("Front Queue : %d\n", Queue->Front->Data);
return 1;
}
int RearPrint(LinkedQueue* Queue)
{
if (Queue->Count == 0)
{
return -1;
}
else
printf("Rear Queue : %d\n", Queue->Rear->Data);
return 1;
}
int main()
{
Node* Popped = NULL;
LinkedQueue* Queue;
LQ_CreateQueue(&Queue);
int i = 0;
int N;
printf("연산 횟수를 입력하세요.\n");
scanf("%d", &N);
for (i = 0; i < N; i++)
{
char command[20];
scanf("%s", command);
if (strcmp("push", command) == 0)
{
int tmp=0;
scanf("%d", &tmp);
LQ_Enqueue(Queue, LQ_CreateNode(tmp));
}
else if (strcmp("pop", command) == 0)
{
Popped = LQ_Dequeue(Queue);
printf("%d\n", Popped->Data);
}
else if (strcmp("size", command) == 0)
{
printf("%d\n", Queue->Count);
}
else if (strcmp("empty", command) == 0)
{
if (LQ_IsEmpty)
printf("1\n");
else
printf("0\n");
}
else if (strcmp("front", command) == 0)
{
frontPrint(Queue);
}
else if (strcmp("back", command) == 0)
{
RearPrint(Queue);
}
}
return 0;
}
[실행결과]
10
push
1
push
2
push
3
push
4
push
5
pop
1
pop
2
pop
3
pop
4
pop
5
0 XDK (+0)
유익한 글을 읽었다면 작성자에게 XDK를 선물하세요.
-
좋아요 1 답글 달기 신고
-
좋아요 1 답글 달기 신고