2019~2020/자료구조
스택 함수
유진
2019. 4. 9. 10:13
반응형
#include<stdio.h>
#define STACK_SIZE 5 // 스택의 사이즈를 5로 정의
typedef int element; // int형을 스택 element의 자료형으로
element stack[STACK_SIZE]; // 자료 형 element를 저장할 수 있는 공간을 스택 사이즈만큼
int top=-1; // 스택의 초기 값을 -1로 저장하여 공백상태로
void push(element item);
element pop();
element peek();
int main()
{
peek();
pop();
push(99);
printf("입력된 스택 %d\n",peek());
push(99);
printf("입력된 스택 %d\n",peek());
push(88);
printf("입력된 스택 %d\n",peek());
push(77);
printf("입력된 스택 %d\n",peek());
push(55);
printf("입력된 스택 %d\n",peek());
push(44);
printf("출력 스택 %d\n",pop());
printf("출력 스택 %d\n",pop());
printf("출력 스택 %d\n",pop());
printf("출력 스택 %d\n",pop());
printf("출력 스택 %d\n",pop());
printf("출력 스택 %d\n",pop());
}
void push(element item) // 스택의 삽입 연산 item = "C"
{
if(top >= STACK_SIZE-1) // 스택이 이미 FULL 상태인 경우
{
printf("Stack is Full!\n");
return;
}
else stack[++top]=item;
}
element pop() // 스택의 삭제 연산, pop은 꺼내다
{
if(top == -1){
printf("Stack is Empty!!\n");
return 0;
}
else return stack[top--]; // 반환 값은 top이 가리키는 값이고 top 포인터는 1개 감소
}
element peek() // 스택의 조회연산
{
if(top == -1)
{
printf("Stack is Empty!!\n");
return 0;
}
else return stack[top]; // 반환값은 top이 가리키는 값이고, top 포인터는 변함 없음
}
/*
Stack is Empty!!
Stack is Empty!! // 꺼낼 거 X
입력된 스택 99
입력된 스택 88
입력된 스택 77
입력된 스택 66
입력된 스택 55
Stack is Full! // 스택의 범위를 벗어남
출력 스택 55 // 맨위에 있는 값
출력 스택 66
출력 스택 77
출력 스택 88
출력 스택 99
Stack is Empty!! // 꺼낼 거 X
출력 스택 0 // 0을 되돌려줌
--------------------------------
Process exited after 0.01508 seconds with return value 0
계속하려면 아무 키나 누르십시오 . . .
*/
반응형