* Computer Science/C

6. stack, queue

soicem 2017. 12. 10. 03:40

 dfs와 bfs를 구현할 때 stack과 bfs를 사용해야함으로 구현


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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#define STACK_SIZE    100
 
struct Stack{
    int stk[STACK_SIZE];
    int top;
};
 
void push(struct Stack *stk, int val){
    if(stk->top <100){
        stk->stk[stk->top ++= val;
        
    } 
}
 
int pop(struct Stack *stk){
    int v;
    if(stk->top > 0){
        v = stk->stk[--(stk->top)];
        stk->stk[stk->top] = NULL;
        return v;
    } else {
        return NULL;
    }    
}
 
int peek(struct Stack *stk){
    return stk->stk[stk->top - 1];
}
 
void initStk(struct Stack *stk){
    stk->top = 0;
}
 
int main(){
    int i = 0;
    unsigned int vals[STACK_SIZE] = {462559488184843169};
 
    struct Stack stk;
    initStk(&stk);
    for(i = 0; i< 10; i++){
        push(&stk, vals[i]);
    }
    for(i = 0; i< 10; i++){
        printf("%d "pop(&stk));
    }
    printf("\n");
 
    return 0;
}
 
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#define QUE_SIZE    100
 
struct Queue{
    int que[QUE_SIZE];
    int left;
    int right;
};
 
void initQueue(struct Queue * que){
    que->left = 0;
    que->right = 0;
}
 
void enqueue(struct Queue * que, int val){
    if(que->right < QUE_SIZE){
        que->que[que->right++= val;
    } 
}
 
int dequeue(struct Queue * que){
    int v;
    if(que->left < que->right){
        v  = que->que[que->left];
        que->que[(que->left)++= NULL;
        return v;
    } else if(que->left == que->right){
        que->left = 0;
        que->right = 0;
        return NULL;
    }
    
    
}
 
 
int main(){
    int i = 0;
    unsigned int vals[10= {462559488184843169};
 
    struct Queue que;
    initQueue(&que);
    for(i =0; i<10; i++){
        enqueue(&que, vals[i]);
    }
    for(i =0; i<10; i++){
        printf("%d ", dequeue(&que));
    }
    printf("\n");
    return 0;
}
 
cs


'* Computer Science > C' 카테고리의 다른 글

5. 함수 포인터  (0) 2017.12.08
1. gcd, quickSort, swap  (0) 2017.12.06