02 December 2010

Stack implementation in C

Hi folks,

I've written a stack implementation in C from sometime ago, and I'd like to share with you.

#ifndef STACK_H
#define STACK_H

#define STACK_SIZE 100

struct stack
{
int data[STACK_SIZE];
int top;
};

void init(struct stack*);
void push(struct stack*, int);
int pop(struct stack*);
int peek(struct stack*);
int is_empty(struct stack*);
int is_full(struct stack*);
void print(struct stack*);
int count(struct stack*);

#endif



#include <stdio.h>
#include <errno.h>
#include "stack.h"

void init(struct stack *s)
{
s->top = -1;
}

void push(struct stack *s, int value)
{
if (!is_full(s))
s->data[++(s->top)] = value;
else
fprintf(stderr, "StackOverFlow\n");
}

int pop(struct stack *s)
{
int ret = peek(s);
if (errno == 0)
s->top--;
errno=0; // non-throw the exception
return ret;
}

int peek(struct stack *s)
{
if (!is_empty(s))
return s->data[s->top];
else
{
fprintf(stderr, "StackUnderFlow\n");
errno = 200; // throw an exception to the calling method (in C way)
return -1;
}
}

int is_empty(struct stack *s)
{
return (s->top == -1);
}

int is_full(struct stack *s)
{
return (s->top == STACK_SIZE-1);
}

void print(struct stack *s)
{
int i;
for (i=0; i<= s->top ; i++)
{
printf("%i\n", s->data[i]);
}
}

int count(struct stack *s)
{
return s->top + 1;
}

No comments: