반응형

스택은 선형데이터 구조로 LIFO(Last In First Out)의 형태를 나타냅니다.
데이터를 입력할 때는 Push, 꺼낼 때는 Pop이라고 합니다.
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
// Stack structure
struct Stack {
int data[MAX_SIZE];
int top;
};
// Initialize stack
void init(struct Stack *s) {
s->top = -1;
}
// Push element to stack
void push(struct Stack *s, int x) {
if (s->top == MAX_SIZE - 1) {
printf("Error: stack overflow\n");
return;
}
s->data[++s->top] = x;
}
// Pop element from stack
int pop(struct Stack *s) {
if (s->top == -1) {
printf("Error: stack underflow\n");
return -1;
}
return s->data[s->top--];
}
// Check if stack is empty
int is_empty(struct Stack *s) {
return s->top == -1;
}
// Get top element of stack
int top(struct Stack *s) {
if (s->top == -1) {
printf("Error: stack is empty\n");
return -1;
}
return s->data[s->top];
}
int main() {
struct Stack s;
init(&s);
push(&s, 1);
push(&s, 2);
push(&s, 3);
printf("Top element is %d\n", top(&s));
printf("Popped element is %d\n", pop(&s));
if (is_empty(&s)) {
printf("Stack is empty\n");
} else {
printf("Stack is not empty\n");
}
return 0;
}

반응형
'프로그래밍 > C' 카테고리의 다른 글
C언어 큐(Queue) (0) | 2023.02.11 |
---|---|
[프로그래머스] 숫자 찾기 - C (0) | 2023.01.11 |
[프로그래머스] 약수 구하기 - C (0) | 2023.01.11 |
[프로그래머스] 7의 개수 - C (0) | 2023.01.11 |