[데이터 구조] C 언어 구현: 창고

Stack.h
#ifndef STACK_H
#define STACK_H

#include 
#include 

typedef signed int ssize_t;

typedef struct StackNode_struct
{
	int data;
	struct StackNode_struct * Prev;
} StackNode_t;

typedef struct
{
	StackNode_t * Top;
	StackNode_t * Bottom;
	size_t Count;
} Stack_t;

bool Stack_Init(Stack_t * stack);
bool Stack_Push(Stack_t * stack, int data);
bool Stack_Pop(Stack_t * stack, int * data);
bool Stack_Top(Stack_t * stack, int * data);
bool Stack_IsEmpty(const Stack_t * stack);
ssize_t Stack_Count(const Stack_t * stack);

#endif

Stack.c
#include 
#include "Stack.h"

bool Stack_Init(Stack_t * stack)
{
	StackNode_t * node = NULL;

	if(!stack)
		return false;

	node = malloc(sizeof(StackNode_t));
	if(!node)
		return false;
	
	node->Prev = NULL;
	node->data = 0;

	stack->Top = node;
	stack->Bottom = node;
	stack->Count = 0;

	return true;
}

bool Stack_Push(Stack_t * stack, int data)
{
	StackNode_t * node = NULL;

	if(!stack)
		return false;
	
	node = malloc(sizeof(StackNode_t));
	if(!node)
		return false;
	
	node->data = data;
	node->Prev = stack->Top;

	stack->Top = node;
	stack->Count++;

	return true;
}

bool Stack_Pop(Stack_t * stack, int * data)
{
	StackNode_t * node = NULL;

	if(!stack)
		return false;
	
	if(stack->Count == 0)
		return false;
	
	*data = stack->Top->data;

	node = stack->Top;
	stack->Top = node->Prev;
	stack->Count--;
	free(node);

	return true;
}

bool Stack_Top(Stack_t * stack, int * data)
{
	if(!stack)
		return false;
	
	if(stack->Count == 0)
		return false;
	
	*data = stack->Top->data;

	return true;
}

bool Stack_IsEmpty(const Stack_t * stack)
{
	if(!stack)
		return false;
	
	return stack->Count == 0;
}

ssize_t Stack_Count(const Stack_t * stack)
{
	if(!stack)
		return -1;
	
	return stack->Count;
}

좋은 웹페이지 즐겨찾기