数据进栈出栈--C语言计算器

来源:互联网 发布:淘宝网页设计与制作 编辑:程序博客网 时间:2024/05/29 11:44
/*    

注意!!!本人水平有限只能进行加减乘除操作  


数据栈: NULL<--operator<--operator<--operator<---operator.....

     操作符栈: NULL<--operand<--operand<--operand<--operand.....
 
1 两个所用的入栈,出栈,栈为空的函数都是一样的.
    2 判断运算符的优先级然后进行操作
3 将计算的结果再次压入栈中
*/
#include <stdio.h>
#include <stdlib.h>


struct stack_node
{
int data;
struct stack_node* next;


};


typedef struct stack_node stack_list;
typedef stack_list* link;


link operator = NULL;
link operand = NULL;


link push(link stack,int value)//数据入栈 
{
link new_node;
new_node = (link)malloc(sizeof(stack_list));
if(!new_node)
{
printf("faliur!\n");
return NULL;
}
new_node->data = value;
new_node->next = stack;
stack = new_node;

return stack;
}
link pop(link stack,int *value)//数据出栈 
{
link top;

if(stack != NULL)
{
top = stack;
stack = stack->next;
*value = top->data;
free(top);
return stack;
}
else
{
*value = -1;
}

}


int empty(link stack)//判断栈中数据是否为空 
{
if(stack == NULL)
{
return 1;
}
else
{
return 0;
}


}


int isoperator(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 get_value(int op,int operand1,int operand2)//将两个数据和和一个运算符当成参数进行运算返回计算结果 
{
switch((char)op)
{
case '*': return (operand2 * operand1);
case '/': return (operand2 / operand1);
case '+': return (operand2 + operand1);
case '-': return (operand2 - operand1);
}


}




int main(void)
{
char exp[100];
int op = 0;
int operand1 = 0;
int operand2 = 0;
int result = 0;
int pos = 0;

printf("input:\n");
scanf("%s",exp);

while(exp[pos] != '\0' && exp[pos] != '\n')
{
if(isoperator(exp[pos]))//判断是否是运算符 
{
if(!empty(operator))//如果栈为空(此栈为运算栈) 
{
while(!empty(operator) && priority(exp[pos]) <= priority(operator->data))//判断运算符的优先级 
{                                                                 //注意!empty()在前
operator= pop(operator,&op);//取出一位操作符 
operand = pop(operand,&operand1);//取出一位数据 
operand = pop(operand,&operand2);//取出另一位数据 

operand = push(operand,get_value(op,operand1,operand2));//计算数值然后找压入栈中

}
}
        
      operator = push(operator,exp[pos]);//将第一个数据压入栈中 
}
else //如果不是运算符将数据压入栈中 
{
operand = push(operand,exp[pos]-48);
}

pos++;

}
//将栈中的数据全部取出进行计算 
while( !empty(operator))
{
operator = pop(operator,&op);
operand = pop(operand,&operand1);
operand = pop(operand,&operand2);
 
operand = push(operand,get_value(op,operand1,operand2));
}
operand = pop(operand,&result);//取出栈中的最后结果 
printf("元素 [%s] 结果: %d\n",exp,result);

system("pause"); 
return 0;
}
原创粉丝点击