Today
Total
Archives
05-20 12:39
관리 메뉴

tony9402

[영상처리 스터디] Queue 구현을 조금 개선시키기 본문

알고리즘/공부

[영상처리 스터디] Queue 구현을 조금 개선시키기

ssu_gongdoli 2019. 1. 14. 02:49
반응형

앞에 글에선 큐가 작동하는 과정과 간단한 소스코드를 작성하였다. 그 소스코드를 이용하여 어떤 알고리즘을 만들때 각 큐에 대한 함수를 엄청 많이 만들어야 한다. 이번 글에선 이를 한번 개선시켜보자.




먼저 Queue *head와 Queue *tail을 하나의 구조체로 묶고 size라는 변수까지 추가하면 깔끔해지겠다. 



1. 새로운 구조체 만들기


1
2
3
4
5
6
7
8
typedef struct
{
    Queue *head;
    Queue *tail;
    int size = 0;
}qq;
 
typedef qq* Q;
cs




2. init() 함수 큐를 인자로 받고 그 큐를 초기화하는 함수로 바꾸면 된다.


1
2
3
4
5
6
7
8
void init(Q q)
{
    q->head = (Queue*)malloc(sizeof(Queue));
    q->head->next = NULL;
    q->tail = q->head;
    q->size = 0;
    return;
}

cs




3. push(int data)함수도 큐를 인자로 받자. (여기서 조심해야할껀 size까지 사용하기 때문에 push하면 size를 증가시켜줘야한다.)


1
2
3
4
5
6
7
8
9
void push(Q q, int data)
{
    Queue *New = (Queue*)malloc(sizeof(Queue));
    New->next = NULL;
    q->tail->data = data;
    q->tail->next = New;
    q->tail = New;
    q->size++;
}

cs



4. pop()함수도 마찬가지로 큐를 인자로 받자.


1
2
3
4
5
6
7
void pop(Q q)
{
    Queue *del = q->head;
    q->head = q->head->next;
    free(del);
    q->size--;
}
cs




5. IsEmpty()함수도 큐를 인자로 받자. 여기서 IsEmpty()함수를 조금 더 간단히 만들 수 있다.


1
2
3
4
5
int IsEmpty(Q q)
{
    return !q->size// return q->size == 0;
    //return q->head == q->tail;
}

cs



이를 전체 다 짜면 아래와 같다.


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
#include<stdio.h>
#include<stdlib.h>
 
struct queue
{
    struct queue *next;
    int data;
};
 
typedef struct queue Queue;
 
typedef struct
{
    Queue* head;
    Queue* tail;
    int size;
}qq;
 
typedef qq* Q;
 
void init(Q q)
{
    q->head = (Queue*)malloc(sizeof(Queue));
    q->head->next = NULL;
    q->tail = q->head;
    q->size = 0;
    return;
}
 
void push(Q q, int data)
{
    Queue *New = (Queue*)malloc(sizeof(Queue));
    New->next = NULL;
    q->tail->data = data;
    q->tail->next = New;
    q->tail = New;
    q->size++;
}
 
void pop(Q q)
{
    Queue *del = q->head;
    q->head = q->head->next;
    free(del);
    q->size--;
}
 
int front(Q q)
{
    return q->head->data;
}
 
int IsEmpty(Q q)
{
    return !q->size// return q->size == 0;
    //return q->head == q->tail;
}
 
int main()
{
    Q first = (Q)malloc(sizeof(qq));
    Q second = (Q)malloc(sizeof(qq));
    init(first);
    init(second);
 
    for (int i = 0; i < 10; i++)
    {
        push(first, i);
    }
    for (int i = 10; i < 20; i++)
    {
        push(second, i);
    }
 
    printf("first :\n");
    while (!IsEmpty(first))
    {
        printf("%d\n"front(first));
        pop(first);
    }
 
    printf("Second :\n");
    while (!IsEmpty(second))
    {
        printf("%d\n"front(second));
        pop(second);
    }
    return 0;
}

cs


반응형
Comments