Advertisement
Shailrshah

Expression Tree

Sep 25th, 2013
295
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.11 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. struct stack{
  4.     char data;
  5.     struct stack *left, *right, *bottom;
  6. } *top = NULL;
  7. void push(struct stack *newNode){
  8.     if(top) newNode->bottom = top;
  9.     top = newNode;
  10. }
  11. struct stack* pop(){
  12.     struct stack *target = top;
  13.     top = top->bottom;
  14.     target->bottom = NULL;
  15.     return target;
  16. }
  17. void display(struct stack *help){
  18.     if(help){
  19.         display(help->left);
  20.         display(help->right);
  21.         printf("%c", help->data);
  22.     }
  23. }
  24. int main(){
  25.     char postfix[20];
  26.     printf("Enter the expression(oprands can be A-Z or 0-9): ");
  27.     gets(postfix);
  28.     for (int i = 0; postfix[i] != '\0'; i++){
  29.         struct stack *newNode = (struct stack*) malloc(sizeof(struct stack));
  30.         newNode->data = postfix[i]; newNode->bottom = NULL;
  31.         if((newNode->data >= 'A' && newNode->data <= 'Z')||(newNode->data >= '0' && newNode->data <= '9')){
  32.             newNode->left = newNode->right = NULL;
  33.             push(newNode);
  34.         }
  35.         else{
  36.             if(!top->bottom) goto end;
  37.             newNode->right = pop(); newNode->left = pop();
  38.             push(newNode);
  39.         }
  40.     }
  41.     if(!top->bottom) display(top);
  42.     else end: printf("\nNot a valid postfix expression.");
  43.     return 0;
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement