1 분 소요

Stack

이번 목표는 Stack을 C언어로 구현하는거이다.

Stack이란 영어로 쌓아놓은 더미이다.

LIFO(Last in First Out)방식으로 가장 최근에 들어온 데이터가 가장 먼저 나가는 것이다.

기능

스택에 기본 기능들은 init, push, pop, size, empty, top이다.

init -> 스택 초기화

push -> 데이터 삽입

pop -> 가장 위에 데이터 추출

size -> 스택 크기 확인

empty -> 스택이 비어있는지 유무 확인

top -> 가장 위에 데이터 확인

구현

#include <stdio.h>

typedef struct {
	int arr[999];
	int top;
}stack;

void init(stack* s)
{
	s->top = -1;
}
void push(stack *s,int num)
{
	s->top++;
	s->arr[s->top] = num;
	printf("___push___\npush %d, top is %d\n",num,s->top);
	return;
}
int pop(stack *s)
{
	if(s->top ==-1 )
	{
		printf("___pop___\nstack is empty\n");
		return -1;
	}
	printf("___pop___\npop %d, top is %d\n",s->arr[s->top],s->top-1);
	return s->arr[s->top--];
}
int size(stack *s)
{
	printf("___size___\nsize is %d\n",s->top+1);
	return s->top+1;
}
int empty(stack *s)
{
	if (s->top == -1)
	{
		printf("___empty___\nstack is empty\n");
		return 1;
	}
	else
	{
	printf("___empty___\nstack is not empty\n");
		return 0;
	}
	
}
int top(stack *s)
{
	if(s->top ==-1)
	{
		printf("___top___\nstack is empty\n");
		return -1;
	}
	printf("___top___\ntop value is %d\n",s->arr[s->top]);
	return s->arr[s->top];
}
int main()
{
	stack s;
	init(&s);
	push(&s,1);
	push(&s,10);
	pop(&s);
	top(&s);
	empty(&s);
	size(&s);
	pop(&s);
	pop(&s);
		
	
	return 0;
}

결과

___push___
push 1, top is 0
___push___
push 10, top is 1
___pop___
pop 10, top is 0
___top___
top value is 1
___empty___
stack is not empty
___size___
size is 1
___pop___
pop 1, top is -1
___pop___
stack is empty

댓글남기기