Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include <stdlib.h>
- #include<string.h>
- char stack[100];
- short top = -1;
- char cima()
- {
- return top == -1 ? 0 : stack[top];
- }
- char pop()
- {
- char s = top == -1 ? 0 : stack[top];
- stack[top--] = 0;
- return s;
- }
- void push(char x)
- {
- if (top != 99)
- stack[++top] = x;
- }
- int par=0;
- int priority(char x)
- {
- switch (x)
- {
- case '(':
- par++;return 0;
- case ')':
- if(--par<0){
- printf("\nUnbalanced parenthesis\n");
- exit(1);
- }return 1;
- case '=':
- return 2;
- case '+':
- case '-':
- return 3;
- case '*':
- case '/':
- return 4;
- case '^':
- return 5;
- }
- char z[]="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
- for(int a=0;a<strlen(z);a++)if(z[a]==x)return-1;
- return -2;
- }
- void printOp(char z[], int pun)
- {
- if (pun)
- {
- z[pun] = 0;
- printf("%s ", z);
- }
- }
- void spellCheck(char x[]){
- int p,last=0;
- for (int a = 0; a < strlen(x); a++){
- p = priority(x[a]);
- if(p>2&&last>2){
- printf("\nConsecutive operator\n");
- exit(2);
- }
- last=p;
- }
- if(par!=0){
- printf("\nUnbalanced parenthesis\n");
- exit(1);
- }
- }
- void parse(char x[])
- {
- char z[50];
- short pun = 0;
- int p;
- printf("Notazione polacca inversa: ");
- for (int a = 0; a < strlen(x); a++)
- {
- p = priority(x[a]);
- if (p==-2);
- else if (p == -1)
- z[pun++] = x[a];
- else
- {
- printOp(z, pun);
- pun = 0;
- if (p == 0)
- push(x[a]);
- else if (p == 1)
- {
- while (cima() != '(')
- {
- printf("%c ", pop());
- }
- pop();
- }
- else if (priority(cima()) < p)
- push(x[a]);
- else if (priority(cima()) >= p)
- {
- while (priority(cima()) >= p && cima() != '(' && cima() != 0)
- printf("%c ", pop());
- push(x[a]);
- }
- }
- }
- printOp(z, pun);
- while (cima() != 0)
- printf("%c ", pop());
- printf("\n");
- }
- int main()
- {
- char str[200];
- printf("Inserire espressione: ");
- gets(str);
- spellCheck(str);
- parse(str);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement