Below is my implementation of a stack in C
. Is it correct? And/or is there anything that I should fix to make it better in any way?
stack.h
#ifndef STACK_H
#define STACK_H
#define EMPTY_STACK -1
typedef struct stack
{
char ch;
struct stack* prev;
} Stack;
extern Stack* init_stack(void);
extern char pop(Stack*);
extern void push(Stack*, char);
#endif
stack.c
#include "stack.h"
#include "stdlib.h"
Stack* init_stack()
{
Stack* ret = (struct stack*)malloc(sizeof(struct stack));
ret->prev = NULL;
return ret;
}
char pop (Stack* stck)
{
char ret;
if (stck->prev)
{
ret = stck->ch;
Stack* prv = stck->prev;
stck->prev = prv->prev;
stck->ch = prv->ch;
free(prv);
return ret;
}
else
return EMPTY_STACK;
}
void push (Stack* stck, char ch)
{
Stack* new_nd = (struct stack*)malloc(sizeof(struct stack));
new_nd->prev = stck->prev;
new_nd->ch = stck->ch;
stck->prev = new_nd;
stck->ch = ch;
}
Thanks!