Stack postfix
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h> //library untuk memanggil isalnum(untuk menganalisa apakah char tersebut berupa huruf atau angka)
#define max 100
typedef struct stack
{
char data[max];
int top;
}stack;
void push(char data,stack *s)
{
if(s->top < max)
{
s->top = s->top +1;
s->data[s->top] = data;
}else
{
printf("penuh");
}
}
char pop(stack * s)
{
char mencoba1;
mencoba1 = s->data[s->top];
s->top--;
return mencoba1;
}
int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
if(x == '^')
return 3;
return 0;
}
int main()
{
stack s;
s.top = -1;
char tes[max];
scanf("%s",tes);
char *e,x;
e = tes;
while(*e != '\0')
{
if(isalnum(*e)) //jika char tersebut berupa huruf atau angka
printf("%c",*e);
else if(*e == '(')
{
push(*e,&s);
}
else if(*e == '(')
{
while(x=pop(&s) != ')')
{
printf("%c ", x);
}
}else
{
while(priority(s.data[s.top])>=priority(*e))
printf("%c ",pop(&s));
push(*e,&s);
}
e++;
}
while(s.top != -1)
{
printf("%c ",pop(&s));
}
return 0;
}
Komentar
Posting Komentar