查看單個文章
舊 2005-12-17, 01:16 AM   #7 (permalink)
getter
管理員
 
getter 的頭像
榮譽勳章
UID - 6433
在線等級: 級別:96 | 在線時長:9733小時 | 升級還需:64小時級別:96 | 在線時長:9733小時 | 升級還需:64小時級別:96 | 在線時長:9733小時 | 升級還需:64小時級別:96 | 在線時長:9733小時 | 升級還需:64小時級別:96 | 在線時長:9733小時 | 升級還需:64小時級別:96 | 在線時長:9733小時 | 升級還需:64小時
註冊日期: 2002-12-08
住址: 天線星球
文章: 8157
精華: 0
現金: 19955 金幣
資產: 765391 金幣
預設

#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();
}
__________________
在「專業主討論區」中的問題解決後,要記得按一下 http://forum.slime.com.tw/images/stamps/is_solved.gif 按鈕喔,
這是一種禮貌動作。

一樣是在「專業主討論區」中發問,不管問題解決與否,都要回應別人的回答文喔。
不然搞 [斷頭文],只看不回應,下次被別人列入黑名單就不要怪人喔。

天線寶寶說再見啦~ ... 天線寶寶說再見啦~

迪西:「再見~ 再見~」

Otaku Culture Party 關心您 ...
getter 目前離線  
送花文章: 37855, 收花文章: 6441 篇, 收花: 26052 次
回覆時引用此帖