1. 헤더파일 코드
#ifndef __LB_STACK_H__
#define __LB_STACK_H__
#define TRUE 1
#define FALSE 0
typedef int Data;
typedef struct _node
{
Data data;
struct _node * next;
} Node;//단순 연결리스트로 구현
typedef struct _listStack
{
Node * head;
} ListStack;
typedef ListStack Stack;
void StackInit(Stack * pstack);
int SIsEmpty(Stack * pstack);
void SPush(Stack * pstack, Data data);
Data SPop(Stack * pstack);
Data SPeek(Stack * pstack);
#endif
2. 내가 구현한 소스 파일
소소한 고민의 흔적이다.
그림으로 직접 그려보면서 데이터를 입력할때마다 그 데이터를 헤드로 하고
출력 역시 헤드를 한칸씩 옮기며 해주면 되겠다는 생각을 했다.
#include <stdio.h>
#include <stdlib.h>
#include "ListBaseStack.h"
void StackInit(Stack * pstack)
{
pstack->head = NULL;
}
int SIsEmpty(Stack * pstack)
{
if (pstack->head == NULL) return TRUE;
else return NULL;
}
void SPush(Stack * pstack, Data data)
{
Node* temp;
temp = (Node*)malloc(sizeof(Node));
temp->next = pstack->head;
temp->data = data;
pstack->head = temp;
}
Data SPop(Stack * pstack)
{
Data temp;
Node* ptemp;
if (pstack->head == NULL)
{
printf("삐용삐용 에러야 에러!");
exit(-1);//return -1 과 시스템상 동일
}
else
{
temp = pstack->head->data;
ptemp = pstack->head;
pstack->head = pstack->head->next;
free(ptemp);
return temp;
}
}
Data SPeek(Stack * pstack)
{
if (pstack->head == NULL)
{
printf("삐용삐용 에러야 에러!");
exit(-1);//return -1 과 시스템상 동일
}
else
{
return pstack->head->data;
}
}
include <stdio.h>
#include <stdlib.h>
#include "ListBaseStack.h"
void StackInit(Stack * pstack)
{
pstack->head = NULL;
}
int SIsEmpty(Stack * pstack)
{
if(pstack->head == NULL)
return TRUE;
else
return FALSE;
}
void SPush(Stack * pstack, Data data)
{
Node * newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = pstack->head;
pstack->head = newNode;
}
Data SPop(Stack * pstack)
{
Data rdata;
Node * rnode;
if(SIsEmpty(pstack)) {
printf("Stack Memory Error!");
exit(-1);
}
rdata = pstack->head->data;
rnode = pstack->head;
pstack->head = pstack->head->next;
free(rnode);
return rdata;
}
Data SPeek(Stack * pstack)
{
if(SIsEmpty(pstack)) {
printf("Stack Memory Error!");
exit(-1);
}
return pstack->head->data;
}
//거의 코드가 내거랑 유사하다. 실력이 늘어가고 있는걸까? 뿌듯함이 느껴진다.