Convert Infix To Postfix using Stack - C Data Structure

C examples for Data Structure:Stack

Description

Convert Infix To Postfix using Stack

Demo Code

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
typedef struct {
  char ch;/*from   www .jav a  2  s . c om*/
} StackData;

#define Error -9999

typedef struct node {
  int num;
  struct node *next;
} Node, *NodePtr;

typedef struct stackType {
  NodePtr top;
} StackType, *Stack;

Stack initStack() {
  Stack sp = (Stack)malloc(sizeof(StackType));
  sp->top = NULL;
  return sp;
}

int empty(Stack S) {
  return (S->top == NULL);
}

void push(Stack S, int n) {
  NodePtr np = (NodePtr)malloc(sizeof(Node));
  np->num = n;
  np->next = S->top;
  S->top = np;
}
int peek(Stack S) {
  if (empty(S))
    return Error;

  int hold = S->top->num;

  return hold;
}
int pop(Stack S) {
  if (empty(S))
    return Error;

  int hold = S->top->num;

  NodePtr temp = S->top;

  S->top = S->top->next;

  free(temp);

  return hold;
}

int readConvert(char[]);
void printPostfix(char[], int);
char getToken(void);
int precedence(char);

int main() {
  char post[50];
  int n = readConvert(post);
  printPostfix(post, n);
}

int readConvert(char post[]) {
  char token, c;

  StackData temp;

  int h = 0;

  Stack S = initStack();

  printf("Type an infix expression and press Enter\n");

  token = getToken();

  while (token != '\n') {
    if (isdigit(token))
      post[h++] = token;
    else if (token == '(') {
      temp.ch = token;
      push(S, temp.ch);
    }
    else if (token == ')')
      while ((c = pop(S)) != '(') post[h++] = c;
    else {
      while (!empty(S) && precedence(peek(S)) >= precedence(token))
        post[h++] = pop(S);
      temp.ch = token;
      push(S, temp.ch);
    }
    token = getToken();
  }
  while (!empty(S))
    post[h++] = pop(S);
  return h; //the size of the expression
}

void printPostfix(char post[], int n) {
  printf("\nThe postfix form is \n");
  for (int h = 0; h < n; h++)
    printf("%c ", post[h]);
  printf("\n");
}

char getToken() {
  char ch;
  while ((ch = getchar()) == ' '); //empty body
  return ch;
}

int precedence(char c) {
  switch (c) {
  case '(': return 0;
  case '+':
  case '-': return 3;
  case '*':
  case '/': return 5;
  }
}

Related Tutorials