This compiles and runs correctly, but it says "The value is 0" Am I not returning what I should be?
Thanks for any help
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define FAILED -1;
typedef struct node stack;
typedef stack * stack_ptr;
struct node
{
int key;
stack_ptr next;
};
int evaluate(char *);
int isempty(stack_ptr);
void push(stack_ptr *, int);
int pop(stack_ptr *);
void cleanup(stack_ptr *);
void print(stack_ptr);
int main()
{
char str[80];
int res;
stack_ptr top = NULL;
printf("Enter the postfix form expression:\n");
gets(str);
res = evaluate(str);
printf("the result is %d: \n", res);
return (0);
}
int evaluate(char *str)
{
int num=0;
char ch=0;
stack_ptr top = NULL;
while((ch == *str))
{
num;
if (ch == ' ')
{
str++;
continue;
}
if (ch == '+')
num = pop(&top) + pop(&top);
else
if (ch == '*')
num = pop(&top) * pop(&top);
else
while (1)
{
if (isdigit(ch))
{
num = 10*num + (ch -'0');
ch = *++str;
}
else
if (ch == ' ')
break;
else
{
printf("wrong input!\n");
exit (0);
}
}
push(&top, num);
str++;
}
return num;
}
int isempty(stack_ptr top)
{
return (top == NULL);
}
void push(stack_ptr *top, int v)
{
stack_ptr tmp;
tmp = (stack_ptr) malloc(sizeof(stack));
if (tmp == NULL)
{
printf("Out of space!\n");
exit (0);
}
tmp->key = v;
tmp->next = *top;
*top = tmp;
}
int pop(stack_ptr *top)
{
stack_ptr tmp;
int x;
if (isempty(*top))
{
printf("wrong input!\n");
exit (1);
}
tmp = *top;
x = tmp->key;
*top = tmp->next;
free(tmp);
return x;
}
void cleanup(stack_ptr *top)
{
stack_ptr tmp;
while(*top != NULL )
{
tmp = (*top)->next;
free(*top);
*top = tmp;
}
}
void print(stack_ptr top)
{
stack_ptr tmp =top;
if (top != NULL)
while (tmp != NULL)
{
printf("\tvalue is %d\n",tmp->key);
tmp = tmp->next;
}
else
printf("stack is empty\n");
}