I'm implementing this data structure (infix to postfix) using stack.
Basically, I'm testing with push and print, no pop operation. The first stack ie., stack
holds the operator and numbers while the second stack stack_precedence
records precedence. I think both stacks work fine but I don't understand why precedence stack is not printing the precedence numbers and instead returns blank output.
Partial implementation:
#include <iostream>
#include <glib.h>
using namespace std;
int main(int argc, char *argv[])
{
GList *stack = nullptr;
GList *stack_precedence = nullptr;
int size = 0;
for (int i = 0; argv[1][i] != '\0'; i++) {
int precedence = 0;
bool is_precedence_set = false;
switch (argv[1][i]) {
/*
* Precedence order:
* 3) ^
* 2) / *
* 1) + -
* 0) ( )
*/
case '^':
precedence = 3;
is_precedence_set = true;
case '/':
case '*':
if (!is_precedence_set) {
precedence = 2;
is_precedence_set = true;
}
case '+':
case '-':
if (!is_precedence_set) {
precedence = 1;
is_precedence_set = true;
}
case '(':
if (!is_precedence_set) {
precedence = 0;
is_precedence_set = true;
}
stack = g_list_append(
stack, GINT_TO_POINTER(argv[1][i]));
stack_precedence = g_list_append(
stack_precedence, GINT_TO_POINTER(precedence));
size++;
break;
case ')':
if (!is_precedence_set) {
precedence = 0;
is_precedence_set = true;
}
break;
default:
if (argv[1][i] >= '0' and argv[1][i] <= '9') {
precedence = 9;
stack = g_list_append(
stack, GINT_TO_POINTER(argv[1][i]));
stack_precedence = g_list_append(
stack_precedence, GINT_TO_POINTER(precedence));
size++;
}
}
}
cout << "Stack size: " << size << endl;
stack = g_list_first(stack);
while (stack != nullptr) {
char c = GPOINTER_TO_INT(stack->data);
cout << c;
stack = g_list_next(stack);
}
cout << endl;
stack_precedence = g_list_first(stack_precedence);
while (stack_precedence != nullptr) {
char c = GPOINTER_TO_INT(stack_precedence->data);
cout << c;
stack_precedence = g_list_next(stack_precedence);
}
cout << endl;
return 0;
}
I pass in 2+2 as an argument to my program and stack
works printing 2+2 exactly but stack_precedence
returns blank.
My expected outcome is
2+2
919
And not
2+2
blank
Precedences are integers not characters
int c = GPOINTER_TO_INT(stack_precedence->data);
^^^ change here