본문 바로가기

Data Structure/Sample Code

Stack

Stack - Node

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
#include <stdio.h>
#include <malloc.h>
#define EMPTY 0
 
struct node{
    int data;
    struct node *link;
};
typedef struct node stack;
 
stack * get_node()//초기화 함수
{
    stack *tmp;
    tmp = (stack *)malloc(sizeof(stack));
    //tmp->link = EMPTY;
    return tmp;
}
 
void push(stack **top, int data)
{
    stack *tmp;
    tmp = *top;
    *top = get_node();
    (*top)->data = data;
    (*top)->link = tmp;
}
 
 
void pop(stack **top){
    stack *tmp;
    tmp = *top;
    *top = (*top)->link;
    free(tmp);
}
int peek(stack **top){
    stack *tmp;
    int num;
    tmp = *top;
    if (*top == EMPTY)
    {
        printf("Stack is Empty");
        return NULL;
    }
    num = tmp->data;
    return num;
}
 
void main()
{
    stack * top = EMPTY;
    push(&top, 10);
    push(&top, 20);
    push(&top, 30);
    push(&top, 40);
    printf("%d\n", peek(&top));
    pop(&top);
    printf("%d\n", peek(&top));
    pop(&top);
    printf("%d\n", peek(&top));
    pop(&top);
    printf("%d\n", peek(&top));
}
cs
 


'Data Structure > Sample Code' 카테고리의 다른 글

Tree  (0) 2015.08.19
Queue 응용  (0) 2015.08.19
LinkedList  (0) 2015.08.19
Queue  (0) 2015.08.19