#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
#define STACK_LEN 10000
typedef int Data;
typedef struct stack{
Data stackArr[STACK_LEN];
int topIndex;
}Stack;
void stackInit(Stack * pstack); // init
int SIsEmpty(Stack * pstack); // empty
void SPush(Stack * pstack, Data data); //push
Data SPop(Stack * pstack); // pop
Data SSize(Stack * pstack);
Data SPeek(Stack * pstack); //top
int main(void)
{
int num;
char str[6];
int newNum;
//스택생성,초기화
Stack stack;
stackInit(&stack);
scanf("%d",&num);
for(int i=0;i<num;i++)
{
scanf("%s",str);
if(!strcmp(str, "push"))//같으면 0출력
{
scanf("%d",&newNum);
SPush(&stack, newNum);
}
else if(!strcmp(str, "pop"))
{
printf("%d\n",SPop(&stack));
}
else if(!strcmp(str, "size"))
{
printf("%d\n",SSize(&stack));
}
else if(!strcmp(str, "empty"))
{
printf("%d\n",SIsEmpty(&stack));
}
else if(!strcmp(str, "top"))
{
printf("%d\n",SPeek(&stack));
}
}
return 0;
}
void stackInit(Stack * pstack)
{
pstack->topIndex = -1; //빈상태
}
int SIsEmpty(Stack * pstack)
{
if(pstack->topIndex == -1) //빔
return TRUE;
else
return FALSE;
}
void SPush(Stack * pstack, Data data)
{
pstack->stackArr[++(pstack->topIndex)] = data; // 데이터 저장
}
Data SSize(Stack * pstack)
{
return pstack->topIndex+1;
}
Data SPop(Stack * pstack)
{
// int rIdx;
if(SIsEmpty(pstack))
{
return -1;
}
// rIdx = pstack->topIndex; //삭제할 데이터 저장
// pstack->topIndex -= 1;
// return pstack->stackArr[rIdx]; // 삭제되는 값 반환
return pstack->stackArr[(pstack->topIndex)--]; // 한줄코딩
}
Data SPeek(Stack * pstack)
{
if(SIsEmpty(pstack))
{
return -1;
}
return pstack->stackArr[pstack->topIndex]; // 맨위 저장된 값 반환
}
그냥 스택의 개념문제다..!
init,push,pop,peek,size,empty의 함수를 구현하면된다.
문제를 맞춘 후 다른 사람들의 코드를 봤는데 씨플플 라이브러리 부럽당,,,
아 각설하고 !
다른 사람의 코드의 POP부분을 보고 살짝 충격을 받았다
바로
Data SPop(Stack * pstack)
{
// int rIdx;
if(SIsEmpty(pstack))
{
return -1;
}
// rIdx = pstack->topIndex; //삭제할 데이터 저장
// pstack->topIndex -= 1;
// return pstack->stackArr[rIdx]; // 삭제되는 값 반환
return pstack->stackArr[(pstack->topIndex)--]; // 한줄코딩
}
return pstack->stackArr[(pstack->topIndex)--]; //로 바로 리턴해줌으로써 rIdx를 따로 선언해줄 필요가 없기때문이다 !
이러면 프로그램의 효율 또한 올라갈것이다 대박 !!!
쨌든 이제 본격적인 알고리즘,,>? 자료구조가 시작된다..!