๐ก ๋์ ๋ฐฐ์ด ์คํ ์ฝ๋
์๊ฐ ๋ณต์ก๋ 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
'Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [C์ธ์ด] - ์ํ ํ Circular Queue (0) | 2023.01.11 |
|---|---|
| [C์ธ์ด] - ํ Queue (0) | 2023.01.11 |
| [C์ธ์ด] Stack ์คํ - ํ์ํ๊ธฐ์ ๊ณ์ฐ postfix / ๋ฌธ์์ด ์ซ์ ์ ์ํ์ผ๋ก ๋ฐ๊พธ๊ธฐ (0) | 2023.01.11 |
| [C์ธ์ด] Stack ์คํ - ์ค์ํ๊ธฐ์ infix์์ ํ์ํ๊ธฐ์ postfix์ผ๋ก ๋ณํ (0) | 2022.12.23 |
| [C์ธ์ด] Stack ์คํ - ๊ดํธ ๊ฒ์ฌ (0) | 2022.12.13 |