본문 바로가기

코딩/데이터 구조

4. 데이터 구조 - stack의 구조체화

728x90
반응형

 

2024.08.07 - [코딩/데이터 구조] - 3. 데이터 구조 - ADT의 개념과 stack의 이해 및 구현

 

 

위의 링크의 stack 구현은 이해하기는 쉽지만 stack배열과 top이 전역변수로 선언되어 있기 때문에 하나의 프로그램에서 여러 개의 stack을 구현할 수 없다. 그래서 top과 stack 배열을 하나의 구조체로 만들면 여러 개의 스택을 쉽게 만들 수 있게 된다.

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

#define MAX 100

typedef struct { //stack 배열과 top 을 하나의 구조체로 만듬
	int data[MAX]; 
	int top;
}stackType;

void init_stack(stackType* s) {
	s->top = -1; // 구조체 포인터를 받으면 top을 사용하는 것이 아닌 s->top으로 사용함
}

int is_empty(stackType* s) {
	return (s->top == -1);
}

int is_full(stackType* s) {
	return (s->top == MAX - 1);
}



void push(stackType* s, int a) {
	if (is_full(s)) {
		printf("꽉찼다.");
		return;
	}

	s->data[++s->top] = a;
}

int pop(stackType* s) {
	if (is_empty(s)) {
		printf("비어있다.");
		return 0;
	}

	int result = s->data[s->top--];
	return result;
}

int peek(stackType* s) {
	if (is_empty(s)) {
		printf("비어있다.");
		return 0;
	}

	int result = s->data[s->top];
	return result;
}

int main(void) {
	stackType s;

	init_stack(&s);

	push(&s, 1);
	push(&s, 2);
	push(&s, 3);

	printf("%d\n", pop(&s));
	printf("%d\n", pop(&s));
	printf("%d\n", pop(&s));

	return 0;
}

 

반응형