I'm working on a project where I must take an expression in reverse polish notation, push the integers and operators onto a stack, then pop them out off the stack as they are inserted into a binary search tree.
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
struct snode
{
int datum;
struct snode* bottom;
};
struct tnode
{
int datum;
struct tnode* left;
struct tnode*right;
};
struct snode*
push(struct snode* stack, int x) {
struct snode *S = (struct snode*)malloc(sizeof(struct snode));
S->datum = x;
S->bottom = stack;
return S;
}
struct snode* pop(struct snode* stack) {
struct snode *S;
if (stack == NULL)
return NULL;
S = stack->bottom;
free(stack);
return S;
}
int
peek(struct snode* stack){
return stack->datum;
}
struct tnode*
create_node(int x){
struct tnode* tmp;
tmp = (struct tnode*)malloc(sizeof(struct tnode));
tmp->datum = x;
tmp->right = NULL;
tmp->left = NULL;
return tmp;
}
void
print_table(struct tnode *AST){
if(AST !=NULL){
print_table(AST->left);
printf("%d ", AST->datum);
print_table(AST->right);
}
}
struct tnode*
build_tree(struct snode *S)
{
struct tnode* root;
if (S==NULL){
return NULL;
}else{
int top = peek(S);
if (top == 65 || top == 83 || top == 88 || top == 68 || top == 77){
return create_node(top);
}else{
root= create_node(top);
root->right = build_tree(pop(S));
root->left = build_tree(pop(S));
return root;
}
}
}
int
main(int argc, const char *argv[])
{
int i = 1;
struct tnode *tree = NULL;
struct snode *stack = NULL;
while (argv[i]!= NULL){
stack = push(stack, argv[i][0]);
i++;
}
tree = build_tree(stack);
print_table(tree);
return EXIT_SUCCESS;
}
I feel like this should work. Everything compiles clean. I run it by saying
./project 5 4 A
and what comes out is
135208 135224 135208 135240 135208 135224 135208 0 135208 135224 135208 52 0 53 0
when it should be
4 65 5
I think this is happening where because of how I'm pushing the elements on to the stack.
EDIT:
I initialized i so that i = 1.
this is the result I am getting.
134480 134496 134480 0 5 4 5
EDIT2:
I decided to get rid of the atol(argv[i]) and change it to just argv[i][0]. see code.
Now my out put is just
65