#include <stdio.h>
#include <string.h>
#include <math.h>
#define MAX 100

typedef int itemType;
typedef struct {
  itemType item[MAX];
  int count;
} Stack;

/**
 * mengubah count pada Stack menjadi 0
 * @param Stack *s
 * @return void
 */
void inisialisasi(Stack *s) {
  s->count = 0;
};

/**
 * mengecek apakah count pada Stack sama dengan MAX
 * @param Stack *s
 * @return int 1 for true, 0 for false
 */
int cekPenuh(Stack *s) {
  return s->count == MAX;
};

/**
 * mengecek apakah count pada Stack sama dengan 0
 * @param Stack *s
 * @return int 1 for true, 0 for false
 */
int cekKosong(Stack *s) {
  return s->count == 0;
};

/**
 * memasukan nilai bertipe itemType ke dalam Stack
 * @param Stack *s
 * @param itemType x
 * @return void
 */
void push(Stack *s, itemType x) {
  if (cekPenuh(s)) {
    printf("Stack penuh!\n");
  } else {
    s->item[s->count] = x;
    s->count++;
  };
};

/**
 *
 */
itemType pop(Stack *s) {
  itemType temp = -1;
  if (cekKosong(s)) {
    printf("Stack kosong!\n");
  } else {
    s->count--;
    temp = s->item[s->count];
  };
  return temp;
};

void printSegment(int x) {
  printf("\n");
  for (int i = 0; i < x; i++) {
    printf("-");
  };
  printf("\n");
};

void main() {
  printSegment(10);

  Stack tumpukan;
  inisialisasi(&tumpukan);

  char postfix[MAX], kar;
  int opLeft, opRight, hasil;
  printf("Masukan notasi postfix : ");
  scanf("%s", &postfix);
  for (int i = 0; i < strlen(postfix); i++) {
    kar = postfix[i];

    if (kar >= '0' && kar <= '9') {
      push(&tumpukan, (kar - 48));
    } else if ((kar == '+') || (kar == '-') || (kar == '*') || (kar == '/') || (kar == '^')) {
      opRight = pop(&tumpukan);
      opLeft = pop(&tumpukan);
      switch (kar) {
        case '+':
          hasil = opLeft + opRight;
          break;
        case '-':
          hasil = opLeft - opRight;
          break;
        case '*':
          hasil = opLeft * opRight;
          break;
        case '/':
          hasil = opLeft / opRight;
          break;
        case '^':
          hasil = (int)pow(opLeft, opRight);
          break;
        default:
          break;
      };
      push(&tumpukan, hasil);
    };
  };
  if (!cekKosong(&tumpukan)) {
    printf("Hasil %d\n", pop(&tumpukan));
  };

  printSegment(10);
};
