본문 바로가기
자료구조

Stack push pop peek

by chaechaekim 2019. 4. 9.


--------------------------------
Process exited after 0.0512 seconds with return value 12
계속하려면 아무 키나 누르십시오 . . .

Stack is Empty!! 
Stack is Empty!! 
입력된 스택 99 
입력된 스택 99 
입력된 스택 88 
입력된 스택 77 
입력된 스택 55 
Stack is Full! 
출력 스택 55 
출력 스택 77 
출력 스택 88 
출력 스택 99 
출력 스택 99 
Stack is Empty!! 
출력 스택 0 

-------------------------------- 
Process exited after 0.0512 seconds with return value 12 
계속하려면 아무 키나 누르십시오 . . .

#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 포인터는 변함 없음 
}

'자료구조' 카테고리의 다른 글

포인터 실습 1  (0) 2019.05.17
리스트  (0) 2019.05.17
  (0) 2019.05.14
함수 사용  (0) 2019.04.08
ㅎㅎ  (0) 2019.03.26

댓글