1,2, 3 삽입 후 1, 2 빼고 현재 탑원소(3)출력후 남아있는 원소 제거 후에  없는 원소를 뺐을때 오류 문구 나오게 하기


전역변수로 top변수 이용 시 문제점 

1. 하나 이상의 스택을 구현하려면 여러개의 top변수를 사용해야하나?(top1, top2...)

-> 너무 비효율적임

해결: top변수와 스택배열을 하나의 구조체로 결합시켜서 포인터로 이용하기 


코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//1 2 3 삽입 후 1 2 빼고 현재 탑원소(3)출력후 다 빼고 없는 원소를 뺐을때 오류 문구 나오게
#include<stdio.h>
#include<stdlib.h>
#define max 5
int top = -1;
int stack[max];
void push(int x);
void pop();
void peek();
int is_full();
int main()
{
    push(1); push(2); push(3); pop(); pop(); peek(); pop(); pop();
}
void push(int x)
{
    if (is_full())
    {
        fprintf(stderr, "원소가 다찼어요\n");
        return;
    }
    stack[++top] = x;
}
int is_full()
{
    if (top == max - 1// 찼으면 -1 , 아니면 0반환
        return 1;
    else return 0;
}
int is_empty()
{
    return top == -1//비었으면 1 , 아니면 0 반환
}
void pop()
{
    if (is_empty())
    {
        fprintf(stderr, "원소가 없어요\n");
        return;
    }
    top--;
}
 
void peek()
{
    if (is_empty())
    {
        fprintf(stderr, "원소가 없습니다\n");
        return;
    }
    printf("스택의 top 원소는 %d입니다\n"stack[top]);
}
cs


+ Recent posts