컴퓨터 프로그래밍 공부/자료구조와 알고리즘

Stack 구현하기

게임 개발 2024. 8. 2. 17:07
int main()
{
	IntStack s;

	InitializeSTK(&s, 8);

	for (int i = 0; i <= 8; i++)
		PushSTK(&s, i+1);
	for (int i = 0; i <= 8; i++)
		PopSTK(&s, i+1);
	PushSTK(&s, 1);
	PeekSTK(&s, 1);
	ClearSTK(&s);

	for (int i = 0; i <= 4; i++)
		PushSTK(&s, i + 1);

	CapacitySTK(&s);
	SizeSTK(&s);
	IsEmptySTK(&s);
	ClearSTK(&s);
	IsEmptySTK(&s);
	IsFullSTK(&s);
	SearshSTK(&s, 2);
	PrintSTK(&s);
	TerminateSTK(&s);

	return 0;
}

int InitializeSTK(IntStack* s, int max)
{
	s->stk = (int*)calloc(max, sizeof(int));
	s->max = max;
	s->cur = -1;
	return 0;
}

int PushSTK(IntStack* s, int x)
{
	if (s->cur >= s->max-1)
	{
		printf("\n\n스택이 가득 찼습니다!\n추가할 수 없습니다!\n\n");
		return -1;
	}
	s->cur++;
	s->stk[s->cur] = x;
	printf("\n%d의 값이 정상 저장되었습니다!\n", s->stk[s->cur]);
	return 0;
}

int PopSTK(IntStack* s, int* x)
{
	if (s->cur <= -1) 
	{
		printf("\n\n스택 내부에 어떤 값도 저장되어 있지 않습니다!\n\n");
		return -1;
	}
	int deleteNum = s->stk[s->cur];
	s->stk[s->cur] = -1;
	s->cur--;
	printf("\n%d의 값이 정상 삭제되었습니다!\n", deleteNum);
	return 0;
}

int PeekSTK(const IntStack* s, int* x)
{
	if (s->stk[s->cur] == x)
		return 0;
	return -1;
}

void ClearSTK(IntStack* s)
{
	int curvalue = s->cur;
	for (int i = 0; i <= curvalue; i++)
	{
		s->stk[i] = -1;
		s->cur--;
	}
}

int CapacitySTK(const IntStack* s)
{
	printf("스택의 최대 용량은 %d입니다.", s->max);
	return s->max;
}

int SizeSTK(const IntStack* s)
{
	printf("스택의 현재 용량은 %d / %d입니다.", s->cur+1,s->max);
	return s->cur;
}

int IsEmptySTK(const IntStack* s)
{
	if (s->cur == -1)
	{
		printf("\n\n스택은 비워져 있습니다\n\n");
		return 0;
	}
	printf("\n\n스택은 비워져 있지 않습니다!\n\n");
	return -1;
}

int IsFullSTK(const IntStack* s)
{
	if(s->cur >= s->max-1)
	{
		printf("\n\n스택은 가득 채워져 있습니다\n\n");
		return 0;
	}
	printf("\n\n스택은 가득 채워져 있지 않습니다!\n\n");
	return -1;
}

int SearshSTK(const IntStack* s, int x)
{
	for (int i = 0; i <= s->cur; i++)
	{
		if (s->stk[i] == x)
		{
			printf("\n%d의 값은 스택의 %d 인덱스에 저장되어 있습니다!\n", x, i);
			return i;
		}
	}
	printf("\n%d의 값은 스택에 없습니다.\n", x);
	return -1;
}

void PrintSTK(const IntStack* s)
{
	if (s->cur <= -1) {
		printf("\n\n스택은 비워져있습니다.\n값을 출력할 수 없습니다.\n\n");
		return;
	}
	printf("\n\n스택의 모든 값 : ");
	for (int i = 0; i <= s->cur; i++)
	{
		printf("%2d", s->stk[i]);
	}
}

void TerminateSTK(IntStack* s)
{
	free(s->stk);
}

'컴퓨터 프로그래밍 공부 > 자료구조와 알고리즘' 카테고리의 다른 글

AVL  (0) 2024.09.21
버블소트 구현  (0) 2024.08.15
완벽한 해싱 & 유니버설 해싱  (0) 2024.06.15
삽입 정렬과 힙 정렬  (0) 2024.06.12
동적 계획법의 접근 방식  (1) 2024.06.09