1) ์คํ์ ํ์ชฝ์ผ๋ก ๋ค์ด๊ฐ์ ํ์ชฝ์ผ๋ก ๋์ค๋ ์๋ฃ๊ตฌ์กฐ์ด๋ค.
2) ์์ ๊ณ์ฐ ๋ฑ์ ์๊ณ ๋ฆฌ์ฆ์์ ๋ค๋ฐฉ๋ฉด์ผ๋ก ํ์ฉ๋๋ค
1) ์คํ์ ๊ตฌํ ๋ฐฉ๋ฒ์๋
2) ๊ฐ์ฅ ๊ธฐ๋ณธ์ ์ธ ํํ์ ์๋ฃ๊ตฌ์กฐ๋ก, ๊ตฌํ ๋์ด๋๋ ๋ฎ์ํธ
1) ์คํ ์ ์ธ
#include <stdio.h>
#define SIZE 10000 // ์คํ ํฌ๊ธฐ
#define INF 99999999 //
int stack[SIZE]; // ์คํ ํฌ๊ธฐ ์ ์ธ
int top = -1;
2) ์คํ ์ฝ์ ํจ์
void push(int data) {
if (top == SIZE - 1) {
printf("์คํ ์ค๋ฒํ๋ก์ฐ๊ฐ ๋ฐ์ํ์ต๋๋ค.\n");
return;
}
stack[++top] = data;
}
3) ์คํ ์ถ์ถ ํจ์
int pop() {
if (top == -1) {
printf("์คํ ์ธ๋ํ๋ก์ฐ๊ฐ ๋ฐ์ํ์ต๋๋ค.\n");
return -INF;
}
return stack[top--];
}
4) ์คํ ์ ์ฒด ์ถ๋ ฅ ํจ์
void show() {
printf("--- ์คํ์ ์ต์๋จ ---\n");
for (int i = top; i >= 0; i--) {
printf("%d\n", stack[i]);
}
printf("--- ์คํ์ ์ตํ๋จ ---\n");
}
5) ์์ฑ๋ ์คํ ์ฌ์ฉํ๊ธฐ
int main(void) {
push(7);
push(5);
push(4);
pop();
push(6);
pop();
show();
system("pause");
return 0;
}
1) ์คํ ์ ์ธ
#include <stdio.h>
#include <stdlib.h>
#define INF 99999999
typedef struct {
int data;
struct Node *next;
} Node;
typedef struct {
Node *top;
} Stack;
2) ์คํ ์ฝ์ ํจ์
void push(Stack *stack, int data) {
Node *node = (Node*) malloc(sizeof(Node)); node->data = data;
node->next = stack->top;
stack->top = node;
}
3) ์คํ ์ถ์ถ ํจ์
int pop(Stack *stack) {
if (stack->top == NULL) {
printf("์คํ ์ธ๋ํ๋ก์ฐ๊ฐ ๋ฐ์ํ์ต๋๋ค.\n");
return -INF;
}
Node *node = stack->top;
int data = node->data;
stack->top = node->next;
free(node);
return data;
}
4) ์คํ ์ ์ฒด ์ถ๋ ฅ ํจ์
void show(Stack *stack) {
Node *cur = stack->top;
printf("--- ์คํ์ ์ต์๋จ ---\n");
while (cur != NULL) {
printf("%d\n", cur->data);
cur = cur->next;
}
printf("--- ์คํ์ ์ตํ๋จ ---\n");
}
5) ์์ฑ๋ ์คํ ์ฌ์ฉํ๊ธฐ
int main(void) {
Stack stack;
stack.top = NULL;
show(&stack);
push(&stack, 7);
push(&stack, 5);
push(&stack, 4);
pop(&stack);
push(&stack, 6);
pop(&stack);
show(&stack);
system("pause");
return 0;
}