Showing posts with label stack. Show all posts
Showing posts with label stack. Show all posts

02 December 2010

Stack infix in C

Based on the post of "Stack implementation in C", here's Stack infix implementation in C:

// the idea of this example from "Data Structures and Algorithms using C#"
// main_stack_infix.c

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

#define CHAR_TO_INT(x) ((x)-48)

void calc(struct stack*, struct stack*);

int main(void)
{
struct stack s1, s2;
char *equation = "1 + 2 - 9 ";
int count=0;

init(&s1);
init(&s2);

while (*equation != '\0')
{
if (count == 2)
{
calc(&s1, &s2);
count=1;
}

if (isdigit(*equation) != 0)
{
push(&s1, CHAR_TO_INT(*equation));
count++;
}else if (ispunct(*equation) != 0)
{
push(&s2, *equation);
}
equation++;
}
printf("%i\n", peek(&s1));
return 0;
}

void calc(struct stack *s1, struct stack *s2)
{
int x = pop(s1);
int y = pop(s1);
int op = pop(s2);
int ret = 0;

switch (op)
{
case '+':
ret = y+x;
break;
case '-':
ret = y-x;
break;
case '*':
ret = y*x;
break;
case '/':
ret = y/x;
break;
}

push(s1, ret);
}

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;
}