SHARE
TWEET

Untitled

a guest Nov 19th, 2019 90 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<ctype.h>
  4. #include<math.h>
  5. typedef struct node
  6. {
  7. char info;
  8. struct node *lchild,*rchild;
  9. }NODE;
  10. NODE * create_tree(char postfix[])
  11. {
  12. NODE *newnode, *stack[20];
  13. int i=0, top = -1;
  14. char ch;
  15. while((ch=postfix[i++])!='\0')
  16. {
  17. newnode = (NODE*)malloc(sizeof(NODE));
  18. newnode->info = ch;
  19. newnode->lchild = newnode->rchild = NULL;
  20. if(isalnum(ch))
  21. stack[++top]=newnode;
  22. else
  23. {
  24. newnode->rchild = stack[top--];
  25. newnode->lchild = stack[top--];
  26. stack[++top]=newnode;
  27. }
  28. }
  29. return(stack[top--]);
  30. }
  31. float eval(NODE *root)
  32. {
  33. float num;
  34. switch(root->info)
  35. {
  36. case '+' : return (eval(root->lchild) + eval(root->rchild));
  37. case '-' : return (eval(root->lchild) - eval(root->rchild));
  38. case '*' : return (eval(root->lchild) * eval(root->rchild));
  39. case '/' : return (eval(root->lchild) / eval(root->rchild));
  40. case '^' : return (pow(eval(root->lchild), eval(root->rchild)));
  41. default: if(isalpha(root->info))
  42. {
  43. printf("\n%c = ",root->info);
  44. scanf("%f",&num);
  45. return(num);
  46. }
  47. else
  48. return(root->info - '0');
  49. }
  50. }
  51. int main()
  52. {
  53. char postfix[30];
  54. float res;
  55. NODE * root = NULL;
  56. printf("\nEnter a valid Postfix expression\n");
  57. scanf("%s",postfix);
  58. root = create_tree(postfix);
  59. res = eval (root);
  60. printf("\nResult = %f",res);
  61. return 0;
  62. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top