[C] stack 구현

숲사람·2022년 5월 4일
0

assert() 로 유닛테스트 수행. struct stack에 함수 포인터를 추가. stack_init()함수에서 콜백함수 등록.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>

struct stack {
	int top;
	int stack_size;
	int *arr;
	bool (*is_empty)(struct stack *);
	void (*push)(struct stack *, int);
	int (*pop)(struct stack *);
};

bool cb_is_empty(struct stack *s)
{
	if (s->top == -1)
		return true;
	return false;
}

void cb_push(struct stack *s, int val)
{
	s->arr[++(s->top)] = val;
}

int cb_pop(struct stack *s)
{
	if (!s->is_empty(s))
		return s->arr[s->top--];
	return -1;
}

struct stack *stack_init(int size)
{
	struct stack *s = (struct stack *)calloc(1, sizeof(struct stack));
	if (s == NULL) return NULL;
	s->top = -1;
	s->stack_size = size;
	s->arr = (int *)calloc(size, sizeof(int));
	if (s->arr == NULL) return NULL;
	s->is_empty = cb_is_empty;
	s->push = cb_push;
	s->pop = cb_pop;
	return s;
}

void unit_test(struct stack *myst)
{
	myst->push(myst, 1);
	myst->push(myst, 2);
	myst->push(myst, 3);
	myst->push(myst, 4);
	myst->push(myst, 5);
	
	for (int i = 5; i > 0; i--)
		assert(myst->pop(myst) == i);
	assert(myst->pop(myst) == -1);
	assert(myst->top == -1);
}

#define TEST 1
int main(int argc, char *argv[])
{
	struct stack *myst = stack_init(10);
#if TEST
	unit_test(myst);
#endif
	printf("%s\n", argv[1]);

	return 0;
}
profile
기록 & 정리 아카이브 용도 (보다 완성된 글은 http://soopsaram.com/documentudy)

0개의 댓글