#include <stdio.h>
#define S 50
int stk[S]={0},top=-1;
posfix( char*in, char*out )
{
int i=0,o=0;
char chk;
while( in[i] != '\0')
{
chk = in[i++];
switch (chk)
{
case '(':
push(stk,chk);
break;
case ')':
while ( stk[top] != '(' )
out[o++];
pop(stk);
break;
case '+':
case '-':
case '*':
case '/':
while ( pochk(stk[top]) >= pochk(chk) )
out[o++] = pop(stk);
push(stk,chk);
break;
default:
out[o++] = chk;
break;
}
}
while ( top > -1 )
out[o++] = pop(stk);
out[o] = '\0';
}
pochk( int chk )
{
int i;
int n[6] = {0,1,1,2,2,0};
char o[6] = "(+-*/";
for( i = 0; i < 6; i++ )
if( chk == o[i] ) return n[i];
return;
}
push( int*s, int d )
{
if ( top >= S-1 )
return;
else
s[++top] = d;
return;
}
pop( int*s )
{
int d;
if ( top == -1 )
return;
else
{
d = s[top];
s[top--] = 0;
return d;
}
}
main()
{
char in[S];
char out[S];
clrscr();
printf("in: ");
scanf("%s",in);
posfix(in,out);
printf("\nout: %s",out);
getch();
}
#include <stdio.h>
struct stack
{
int data;
struct stack*next;
}test;
struct stack *stk;
posfix( char*in, char*out )
{
int i=0,o=0;
char chk;
while( in[i] != '\0')
{
chk = in[i++];
switch (chk)
{
case '(':
push(stk,chk);
break;
case ')':
while ( stk->data != '(' )
out[o++];
pop(stk);
break;
case '+':
case '-':
case '*':
case '/':
while ( pochk(stk->data) >= pochk(chk) )
out[o++] = pop(stk);
push(stk,chk);
break;
default:
out[o++] = chk;
break;
}
}
while ( stk->next != NULL )
out[o++] = pop(stk);
out[o] = '\0';
}
pochk( int chk )
{
int i;
int n[6] = {0,1,1,2,2,0};
char o[6] = "(+-*/";
for( i = 0; i < 6; i++ )
if( chk == o[i] ) return n[i];
return;
}
push( struct stack*s, int d )
{
struct stack *new;
new = malloc(sizeof(test));
new->data = d;
new->next = s;
stk = new;
}
pop( struct stack*s )
{
int d;
struct stack*pre,*cur;
pre = NULL;
cur = s;
if (cur != NULL)
{
pre = cur;
d = cur->data;
cur = cur->next;
stk = cur;
free(pre);
return d;
}
}
main()
{
char in[50];
char out[50];
clrscr();
printf("in: ");
scanf("%s",in);
push(stk,0);
posfix(in,out);
printf("\nout: %s",out);
getch();
}
|