前言
- 个人推荐在牛客网刷题(点击可以跳转),主要它登陆后会保存刷题记录进度,重新登录时写过的题目代码不会丢失。
- 个人刷题练习系列专栏:个人CSDN牛客刷题专栏。 牛客数据结构题目位置如下:
问题描述:
给定一个逆波兰表达式,求表达式的值。
输入描述:
[“2”,“1”,“+”,“4”,“*”]
输出描述:
12
举例:
//输入:
["2","1","+","4","*"]
//输出:
12
//输入:
["2","0","+"]
//输出:
2
解法思路:
- 因为输入是逆波兰表达式,因此一定是满足波兰表达式的,即是一个满足数据结构栈的标准输入。因此无需考虑输入错误等其他情况,直接使用栈实现就行,可使用结构体实现栈便可以了。
- 本题中使用的结构体其实可以直接用一个数组来代替,类似上一章节:【牛客刷题专栏】0x03:栈的压入、弹出序列
代码结果:
int evalRPN(char** tokens, int tokensLen ) {
struct{
int integer[10000];
int topIdx;
}str={{0},0};
for(int i=0,j=0;i<tokensLen;i++)
{
if(strcmp(tokens[i],"+")==0)
{
str.integer[str.topIdx-2]=str.integer[str.topIdx-2]+str.integer[str.topIdx-1];//先入栈的加后入栈的
str.topIdx--;
}
else if(strcmp(tokens[i],"-")==0)
{
str.integer[str.topIdx-2]=str.integer[str.topIdx-2]-str.integer[str.topIdx-1];//先入栈的减后入栈的
str.topIdx--;
}
else if(strcmp(tokens[i],"*")==0)
{
str.integer[str.topIdx-2]=str.integer[str.topIdx-2]*str.integer[str.topIdx-1];//先入栈的乘以后入栈的
str.topIdx--;
}
else if(strcmp(tokens[i],"/")==0)
{
str.integer[str.topIdx-2]=str.integer[str.topIdx-2]/str.integer[str.topIdx-1];//先入栈的除以后入栈的
str.topIdx--;
}
else{
str.integer[str.topIdx]=atoi(tokens[i]);//数字入栈
str.topIdx++;
}
}
return str.integer[0];//结果返回,运算结束结果一定是在栈底的
}
重点难点:
- 比较字符串:
要使用 strcmp() == 0 比较字符串,而不是简单的 == ,它只会比较指针是否相同。
tokens[i]是指向字符串的指针(指向以空字符结尾的字符数组的指针),如 “+“或 “1”。注意,输入参数char* tokens是一个二级指针,因此tokens[i]是指向字符串的指针。*
表达式tokens[i]==”+“检查两个指针是否相同(指向相同的内存位置)。
表达式strcmp(tokens[i],”+”)==0将检查两个字符串的内容是否相同。
函数位置:C 标准库 - <string.h>
函数声明: int strcmp(const char *str1, const char *str2) - 字符串转换为一个整数:
C 库函数 int atoi(const char *str) 把参数 str 所指向的字符串转换为一个整数(类型为 int 型)。
这里要使用atoi(),而不是(int)强制转换,因为字符串本质上是数组,是多个元素,而不是一个变量。
函数位置:C 标准库 - <stdlib.h>
函数声明:int atoi(const char *str)
结束语
- 以上就是C数据结构栈实现逆波兰表达式求值及其重点讲解的内容。可以在牛客尝试刷几道单链表题目来练习实践。牛客网刷题(点击可以跳转),可以尝试注册使用。