본문 바로가기
알고리즘/자료구조(C)

스택

by 진진리 2023. 9. 22.
728x90
  • IntStack.h
#ifndef __IntStack
#define __IntStack

typedef struct {
	int max; //스택 용량
	int ptr; //스택 포인터
	int* stk; //스택 첫 요소 포인터
} IntStack;

int Initialize(IntStack* s, int max);

int Push(IntStack* s, int x);

int Pop(IntStack* s, int* x);

int Peek(const IntStack* s, int* x);

void Clear(IntStack* s);

int Capacity(const IntStack* s);

int Size(const IntStack* s);

int IsEmpty(const IntStack* s);

int IsFull(const IntStack* s);

int Search(const IntStack* s, int x);

void Print(const IntStack* s);

void Terminate(IntStack* s);

#endif

 

#ifndef  ~  #endif : 구조체 중복 정의로 인한 오류를 막기 위한 매크로로, __IntStack이 정의되지 않았다면 내부의 정의를 포함하라는 의미

#define : __IntStack을 정의하는 매크로

 

스택에 접근할 때에는 s->stk[s->ptr-1]

ptr은 스택에 있는 요소 개수와 동일하므로 앞으로 데이터를 넣을 빈 자리를 가리키고 있음

 

  • 소스파일 IntStack.c
#include <stdio.h>
#include <stdlib.h>
#include "IntStack.h"

int Initiallize(IntStack* s, int max) { /* 스택 초기화 */
	s->ptr = 0;
	if ((s->stk = calloc(max, sizeof(int))) == NULL) {
		s->max = 0;
		return -1;  //배열 생성 실패
	}
	s->max = max;
	return 0;
}

int Push(IntStack* s, int x) {
	if (s->ptr >= s->max) return -1;  //스택이 가득 참
	s->stk[s->ptr++] = x;
	return 0;
}

int Pop(IntStack* s, int* x) {
	if (s->ptr <= 0) return -1; // 스택이 비어 있음
	*x = s->stk[--s->ptr];
	return 0;
}

int Peek(const IntStack* s, int* x) {
	if (s->ptr <= 0) return -1; // 스택이 비어 있음
	*x = s->stk[s->ptr - 1];
	return 0;
}

void Clear(IntStack* s) {
	s->ptr = 0;
}

int Capacity(const IntStack* s) {
	return s->max;
}

int Size(const IntStack* s) {
	return s->ptr;
}

int IsEmpty(const IntStack* s) {
	return s->ptr <= 0;
}

int IsFull(const IntStack* s) {
	return s->ptr >= s->max;
}

int Search(const IntStack* s, int x) {
	int i;
	for (i = s->ptr - 1; i >= 0; i--)
		if (s->stk[i] == x) return i;
	return -1;
}

void Print(const IntStack* s) {
	int i;
	for (i = 0; i < s->ptr; i++)
		printf("%d ", s->stk[i]);
	putchar('\n');
}

void Terminate(IntStack* s) {
	if (s->stk != NULL)
		free(s->stk);
	s->max = s->ptr = 0;
}

 

 

  • 스택을 사용하는 프로그램 IntStackTest.c
#include <stdio.h>
#include "IntStack.h"

int main(void) {
	IntStack s;
	if (Initialize(&s, 64) == -1) {
		puts("스택 생성에 실패하였습니다.");
		return 1;
	}

	while (1) {
		int menu, x;
		printf("현재 데이터 수 : %d / %d\n", Size(&s), Capacity(&s));
		printf("(1)푸시 (2)팝 (3)피크 (4)출력 (0)종료 : ");
		scanf_s("%d", &menu);

		if (menu == 0) break;
		switch (menu) {
		case 1:
			printf("데이터: ");
			scanf_s("%d", &x);
			if (Push(&s, x) == -1) puts("오류: 푸시에 실패하였습니다.");
			break;

		case 2:
			if (Pop(&s, &x) == -1) puts("오류: 팝에 실패하였습니다.");
			else printf("팝 데이터는 %d입니다.\n", x);
			break;

		case 3:
			if (Peek(&s, &x) == -1) puts("오류: 피크에 실패하였습니다.");
			else printf("피크 데이터는 %d입니다.\n", x);
			break;

		case 4:
			Print(&s);
			break;
		}
	}
	Terminate(&s);
	return 0;
}

 

'알고리즘 > 자료구조(C)' 카테고리의 다른 글

재귀 알고리즘  (0) 2023.09.22
  (0) 2023.09.22
검색 알고리즘  (0) 2023.09.19
구조체  (0) 2023.09.19
배열  (0) 2023.09.19