📄 lianzhan.cpp
字号:
// lianzhan.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
struct stack_node
{
int data;
struct stack_node *next;
};
typedef struct stack_node node;
typedef node *link;
link operater=NULL;
link oprand=NULL;
link push(link stack,int value)
{
link newnode;
newnode=(link)malloc(sizeof(node));
if (!newnode)
{
printf("分配内存失败");
return NULL;
}
newnode->data=value;
newnode->next=stack;
stack=newnode;
return stack;
}
link pop(link stack,int *value)
{
link temp;
if(stack!=NULL)
{
temp=stack;
stack=stack->next;
*value=temp->data;
free(temp);
return stack;
}
else
*value=-1;
}
int empty(link stack)
{
if(stack==NULL)
return 1;
else
return 0;
}
int isoperater(char op)
{
switch (op)
{
case '+':
case '-':
case '*':
case '/': return 1;
default : return 0;
}
}
int priority(char op)
{
switch (op)
{
case '*':
case '/': return 2;
case '+':
case '-': return 1;
default : return 0;
}
}
int getvalue(int op,int op1,int op2)
{
switch ((char)op)
{
case '*': return (op2*op1);
case '/': return (op2/op1);
case '+': return (op2+op1);
case '-': return (op2-op1);
}
}
int main(int argc, char* argv[])
{
char exp[100];
int result=0;
int op1=0;
int op2=0;
int op=0;
int i=0;
printf("输入表达式:");
gets(exp);
while (exp[i]!='\0'&&exp[i]!='\n')
{
if (isoperater(exp[i]))
{
while (!empty(operater)&&priority(exp[i])<=priority(operater->data))
{
operater=pop(operater,&op);
oprand=pop(oprand,&op1);
oprand=pop(oprand,&op2);
oprand=push(oprand,getvalue(op,op1,op2));
}
operater=push(operater,exp[i]);
}
else
oprand=push(oprand,exp[i]-48);
i++;
}
while (!empty(operater))
{
operater=pop(operater,&op);
oprand=pop(oprand,&op1);
oprand=pop(oprand,&op2);
oprand=push(oprand,getvalue(op,op1,op2));
}
oprand=pop(oprand,&result);
printf("表达式的结果是%d\n",result);
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -