반응형
Linked List를 활용한 Stack구현이다.
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 | #include <stdio.h> #include <stdlib.h> typedef struct StackNode{ int data; struct StackNode *link; }StackNode; typedef struct { struct StackNode *top; }StackType; void init(StackType *s) { s->top=NULL; } int is_empty(StackType *s) { return (s->top == NULL); } void stack_push(StackType *s , int data) { StackNode *in_stack = (StackNode*)malloc(sizeof(StackNode)); if(in_stack == NULL) { printf("할당에러\n"); return; } else { in_stack->data = data; in_stack->link = s->top; s->top = in_stack; } } int stack_pop(StackType * s) { int data; if(is_empty(s)) { printf("스택이 비어있음\n"); return -1; } else { StackNode * tmp = s->top; data = tmp->data; s->top = tmp->link; free(tmp); return data; } } int main() { StackType s; init(&s); stack_push(&s,1); stack_push(&s,2); stack_push(&s,3); printf("%d\n",stack_pop(&s)); printf("%d\n",stack_pop(&s)); printf("%d\n",stack_pop(&s)); printf("%d\n",stack_pop(&s)); return 0; } | cs |
반응형
'프로그래밍 > 자료구조' 카테고리의 다른 글
기본 링크드리스트 활용 (0) | 2016.06.08 |
---|---|
유클리드 알고리즘 (0) | 2016.05.18 |
이진 탐색 (0) | 2016.03.08 |
링크드리스트 순차탐색 (0) | 2016.03.07 |
삽입 정렬(Insort Sort) (0) | 2016.03.07 |