表达式求值问题
#include<stdio.h>
#define StackSzie 100
#define QueueSize 100
typedef char DataType;
typedef struct {
char data[100];
int front, rear;
}SeqQueue;
void InitQueue(SeqQueue *Q) {
Q->front = 0;
Q->rear = 0;
}
int QueueEmpty(SeqQueue Q) {
return Q.rear == Q.front;
}
void EnQueue(SeqQueue *Q,DataType x)
{
if ((Q->rear+1)% QueueSize ==Q->front) {
printf("Queue overflow");
}
else {
Q->data[Q->rear] = x;
Q->rear = (Q->rear+1) % QueueSize;
}
}
DataType DeQueue(SeqQueue *Q) {
char x;
if (QueueEmpty(*Q)) return 0;
else {
x = Q->data[Q->front];
Q->front = (Q->front+1)%QueueSize;
return x;
}
}
typedef struct {
DataType data[100];
int top;
}SeqStack;
void InitStack(SeqStack *S) {
S->top = -1;
}
void Push(SeqStack *S, DataType x) {
if (S->top == StackSzie - 1) {
printf("stack overflow");
}
else {
S->top = S->top + 1;
S->data[S->top] = x;
}
}
DataType Pop(SeqStack *S) {
if (S->top == -1) {
printf("stack underflow");
return 0;
}
else
return S->data[S->top--];
}
DataType GetTop(SeqStack S) {
if (S.top == -1) {
printf("stack empty");
return 0;
}
else
return S.data[S.top];
}
int Priority(DataType op) {
switch (op)
{
case '(':
case '#':return 0;
case '-':
case '+':return 1;
case '*':
case '/':return 2;
}
return -1;
}
void CTpostExp(SeqQueue *Q)
{
SeqStack S;
printf("请输入运算表达式,并用#结尾!\n");
char c, t;
InitStack(&S);
Push(&S, '#');
do {
c = getchar();
switch (c)
{
case ' ':break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': EnQueue(Q, c);break;
case '(': Push(&S, c);break;
case ')':
case '#':
do {
t = Pop(&S);
if (t != '(' && t != '#') EnQueue(Q, t);
}while (t != '(' && S.top != -1);
break;
case '+':
case '-':
case '*':
case '/':
while (Priority(c) <= Priority(GetTop(S)))
{
t = Pop(&S);
EnQueue(Q, t);
}
Push(&S, c);
break;
}
} while (c !='#');
printf("\n导入成功!\n");
}
DataType CPostExp(SeqQueue Q) {
SeqStack S;
char ch;
int x, y;
InitStack(&S);
while(!QueueEmpty(Q)) {
ch = DeQueue(&Q);
if (ch >= '0' && ch <= '9')
Push(&S,ch);
else {
y = Pop(&S) - '0';
x = Pop(&S) - '0';
switch (ch)
{
case '+':Push(&S, (char)(x+y+'0'));break;
case '-':Push(&S, (char)(x-y+'0'));break;
case '*':Push(&S, (char)(x*y+'0'));break;
case '/':Push(&S, (char)(x/y+'0'));break;
}
}
}
return GetTop(S);
}
int main(void) {
SeqQueue Q;
InitQueue(&Q);
CTpostExp(&Q);
printf("表达式的运算结果是:%c\n",CPostExp(Q));
printf("表达式的后缀表达式为:");
while (!QueueEmpty(Q))
printf("%2c",DeQueue(&Q));
printf("\n");
}
推荐大家一个小巧轻便的C语言编译工具
点击连接