문자열을 배열에 담을 수 있는 횟수만큼 받고 Queue가 다 차면 Dequeue를 실행하여 배열을 비워주는 코드입니다.

# The source code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#define MAX_SZ 4
typedef int boolean;
 
int true = 1;
int false = 0;
int front;
int rear;
char * que[MAX_SZ];
 
boolean isEmpty()
{
    if (front == rear)
    {
        return true;
    }
    else
    {
        return false;
    }
}
boolean isFull()
{
    if (((rear + 1) % MAX_SZ) == front)
    {
        return true;
    }
    else
    {
        return false;
    }
}
int enque(char * v)
{
    if (isFull() == true)
    {
        printf("Queue is full \n");
        return false;
    }
    else
    {
        rear = (rear + 1) % MAX_SZ;
        que[rear] = v;
        return true;
    }
}
char * deque()
{
    if (isEmpty() == true)
    {
        printf("Queue is empty \n");
        return 0;
    }
    else
    {
        front = (front + 1) % MAX_SZ;
        return que[front];
    }
}
void printQue()
{
    for (int i = 0; i < MAX_SZ; i++)
    {
        printf("%s  ", que[i]);
    }
    return;
}
void main()
{
    char input[30];
    char * s = 0;
    char * c = 0;
    int i = 1;
    while (1)
    {
        scanf_s("%s", input, sizeof(input));
        s = (char *)malloc(strlen(input));
        strcpy_s(s, strlen(input)+1, input); 
        
        if(enque(s) == false)
        {
            printQue();
            printf("\ndeque starts \n");
 
            while (1)
            {
                c = deque();
                if (c == 0)
                {
                    break;
                }
                printf("%s -> ", c);
            }
        }
    }
}
cs

 * sizeof와 strlen의 차이는 예를 들어 char * c = "hello"에서 sizeof(c)는 NULL문자를 포함한 메모리의 할당크기를 바이트단위로 구하는 연산자이고, strlen(c)는 순수하게 문자열"hello"의 길이만을 구하는 함수입니다. strcpy_s를 사용하여 문자열복사를 할 때에는 크기도 같이 넘겨줘야 하는데 strlen를 사용한다면 NULL값을 포함하기 위하여 +1을 해줍니다.

 

# The result

'그 외 공부 > Algorithm' 카테고리의 다른 글

# 8_Contacts with BST  (0) 2017.11.05
# 7_BST(Binary Search Tree)  (0) 2017.11.05
# 5_CircularQueue  (0) 2017.11.05
# 4_Post calculation with stack  (0) 2017.11.05
# 3_Stack  (0) 2017.11.05

+ Recent posts