Algorithm

[C์–ธ์–ด] Stack ์Šคํƒ - ๋™์  ๋ฐฐ์—ด ์Šคํƒ / ๋™์  ๋ฉ”๋ชจ๋ฆฌ ํ• ๋‹น malloc, realloc, free

say! 2022. 12. 13. 16:11
728x90

๐ŸŸก ๋™์  ๋ฐฐ์—ด ์Šคํƒ ์ฝ”๋“œ

์‹œ๊ฐ„ ๋ณต์žก๋„ O(1)

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

typedef int element;

typedef struct {
	element* data;
	int top;
	int capacity; // ํ˜„์žฌ ํฌ๊ธฐ
} StackType;

void init(StackType* s) {
	s->top = -1;
	s->capacity = 1;
	s->data = (element*)malloc(s->capacity * sizeof(element));
}

int is_full(StackType *s) {
	if (s->top == s->capacity - 1)
		return 1;
	else return 0;
}

int is_empty(StackType *s) {
	if (s->top == -1)
		return 1;
	else return 0;
}

// ์‚ฝ์ž…
void push(StackType* s, element item) {
	if (is_full(s)) {
		s->capacity *= 2; // ์šฉ๋Ÿ‰ 2๋ฐฐ๋กœ ๋Š˜๋ฆฌ๊ธฐ
		s->data = (element*)realloc(s->data, s->capacity * sizeof(element));
	}
	s->data[++(s->top)] = item;
}

// ์‚ญ์ œ
int pop(StackType* s) {
	if (is_empty(s)) {
		printf("์Šคํƒ ๊ณต๋ฐฑ ์—๋Ÿฌ\n");
		return;
	}
	else return s->data[(s->top)--];
}


int main(void) {
	StackType s;
	init(&s);
	push(&s, 45);
	push(&s, 87);
	push(&s, 22);
	printf("%d\n", pop(&s));

	free(s.data);

	return 0;

}

 

๐Ÿ”ต ์Šคํƒ

ํ›„์ž…์„ ์ถœ(LIFO)

๋งจ ์œ„์—์„œ๋งŒ ์Šคํƒ์˜ ์ž…์ถœ๋ ฅ ๊ฐ€๋Šฅ, ์Šคํƒ์˜ ์ค‘๊ฐ„์—์„œ ๋ฐ์ดํ„ฐ ์‚ญ์ œ ๋ถˆ๊ฐ€๋Šฅ

 

๐Ÿ”ต malloc, realloc, free

<stdlib.h>์— ์„ ์–ธ๋˜์–ด ์žˆ์Œ

s->data = (int*)malloc(s->capacity * sizeof(int));

calloc๋Š” malloc๊ณผ ๊ฐ™์œผ๋‚˜ ํ• ๋‹น ๋ฉ”๋ชจ๋ฆฌ๋ฅผ 0์œผ๋กœ ์ดˆ๊ธฐํ™”ํ•จ

s->data = (int*)realloc(s->data, s->capacity * sizeof(int));

realloc์€ ํ• ๋‹น๋œ ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ๋‹ค์‹œ ํ• ๋‹นํ•จ, ๊ธฐ์กด์— ํ• ๋‹น๋œ ๋ฉ”๋ชจ๋ฆฌ์— ๋ณ€ํ•จ์€ ์—†์Œ

free(s.data);

์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ๋ฉ”๋ชจ๋ฆฌ๋Š” free ํ•จ์ˆ˜๋กœ ํ•ด์ œํ•ด์ฃผ๊ธฐ, ํ•ด์ œํ•˜๊ณ ์ž ํ•˜๋Š” ๋ฉ”๋ชจ๋ฆฌ์˜ ํฌ์ธํ„ฐ๋ฅผ ์ธ์ž๊ฐ’์œผ๋กœ ์ „๋‹ฌ


 

[C์–ธ์–ด] ๋™์  ๋ฉ”๋ชจ๋ฆฌ ํ• ๋‹น์˜ ์„ธ๊ฐ€์ง€ ๋ฐฉ๋ฒ• malloc, calloc, realloc

๋™์  ๋ฉ”๋ชจ๋ฆฌ ํ• ๋‹น ์šฐ๋ฆฌ๋Š” ์ด์ œ๊ป ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ํ• ๋‹นํ• ๋•Œ ์ •์ ์œผ๋กœ ํ• ๋‹นํ–ˆ์Šต๋‹ˆ๋‹ค. ์–ด๋–ค ๊ฒƒ์ด๋ƒ๋ฉด int arr[100]; ์ด๋ ‡๊ฒŒ ํ• ๋‹น์„ ํ–ˆ์—ˆ์ฃ . ๋ญ ๋ฌธ์ œ์—†์Šต๋‹ˆ๋‹ค. ์‹คํ–‰๋„ ์ž˜ ๋˜๊ตฌ์š”. ํ•˜์ง€๋งŒ ์ด๋Ÿฐ ์ƒํ™ฉ์€ ์กฐ๊ธˆ ๋ถˆ

reakwon.tistory.com