晕 45还是54?楼主!S←S+1处应该是S←S+i吧!
那样s是1一直加到9,结果为45
/*你提供的那个代码是伪代码,我帮你写成了
C
的代码。
你提供的伪代码,我用注释写到了对应的行的后面。
根据你提供的代码还只能转换含有一个字母或
[0,9]
区间内的数字的解析式。
补充了一点栈的基本算法
执行后输出:
a+b*c
新式子(后缀表达式):
a
b
c
*
+
代码使用
Linux
+
GCC
3.4.5
编译通过
July.28th,2009
14:30pm.
main()
在最下边
*/
#include
struct
_stack
{
char
__stack[1024]
int
__top
}
//
模拟栈
inline
init_stack(
struct
_stack
*
p_stack
)
//
初始化栈
{
int
i
=
0
for(
i
=
0
i
<=
1024
i++
)
p_stack->__stack[i]
=
'\0'
p_stack->__top
=
0
}
inline
void
push(
struct
_stack
*
p_stack,
char
p_op
)
//
进栈
{
p_stack->__stack[p_stack->__top]
=
p_op
(
p_stack->__top
)++
}
inline
char
pop(
struct
_stack
*
p_stack
)
//
出栈
{
(
p_stack->__top
)--
return
p_stack->__stack[p_stack->__top]
}
inline
int
precedence(
char
p_char
)
//
比较优先级
{
if(
p_char
==
'+'
||
p_char
==
'-'
)
return
1
else
if(
p_char
==
'/'
||
p_char
==
'*'
)
return
2
else
return
0
}
char
postString[1024]
char
*
infix_to_postfix(
char
*inString
)
{
int
l
=
strlen(
inString
)
struct
_stack
stack
char
p
=
'\0'
int
i
=
0
char
c
=
'\0'
l
=
strlen(
inString
)
//
l
<-
Length
of
inString
for(
i
=
0
i
<=
1024
i++
)
postString[i]
=
'\0'
//
postString
<-
empty
string
init_stack(
&stack
)
//
stack
<-
Empty
stack
for(
i
=
0
i
<=
l
i++
)
//
for
i
<-
0
to
l
{
c
=
inString[i]
//
c
<-
inString[i]
if(
(
c
>=
'0'
&&
c
<=
'9'
)||(
c
>=
'a'
&&
c
<=
'z'
)||(
c
>=
'A'
&&
c
<=
'Z'
)
)
//
if
c
is
an
operand
{
if(
postString[0]
==
'\0'
){postString[0]
=
ccontinue}
sprintf(
postString,
"%s
%c",
postString,
c
)
//
add
c
at
the
end
of
postString
}//
end
if
if(
c
==
'+'
||
c
==
'-'
||
c
==
'*'
||
c
==
'/'
)
//
if
c
is
an
operator
{
if(
stack.__top==0
||
precedence(
stack.__stack
[stack.__top]
)<
precedence(
c
)
)
//
if
stack
is
empty
OR
if
precedence(
stack_top
)<
precedence(
c
)
{
push(
&stack,
c
)
//
push
c
into
stack
}
else
{
while(
precedence(
stack.__stack
[stack.__top]
)>=
precedence(
c
)
)
//
while
precedence(
stack_top
)>=
precedence(
c
)
{
p
=
pop(
&stack
)
//
p
<-
pop
from
stack
sprintf(
postString,
"%s
%c",
postString,
p
)
//
add
p
at
the
end
of
postString
}
//
end
while
push(
&stack,
c
)
//
push
c
into
stack
}
//
end
if
}
//
end
if
}
//
end
for
while(
stack.__top
)
//
while
stack
is
not
empty
{
p
=
pop(
&stack
)
//
p
<-
pop
from
stack
sprintf(
postString,
"%s
%c",
postString,
p
)
//
add
p
at
the
end
of
postString
}
//
end
while
return
postString
}
int
main(
)
{
char
exp[]
=
"a+b*c"
char
*
p
=
0
p
=
infix_to_postfix(
exp
)
printf(
"原式子(中缀表达式):\n\t%s\n新式子(后缀表达式):\n\t%s\n",
exp,
p
)
return
0
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)