[关闭]
@chawuciren 2018-11-21T13:44:42.000000Z 字数 1094 阅读 624

150. Evaluate Reverse Polish Notation

leetcode


Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, /. Each operand may be an integer or another expression.

Note:

Division between two integers should truncate toward zero.
The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.
Example 1:

Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9

解决思路

先初始化两个和一个队列,一个用来放数字,一个用来放符号。队列用来存放排好序的算式。
数字先进栈。碰到第一个符号,进符号的栈。然后按数字-符号-数字的顺序出栈并计算出表达式的值,将该值进队列。然后继续进栈,碰到第二个符号,如果队列不是空的,就将符号-数字进队列,计算出该表达式的值,往后以此类推。

第一个问题

输入的时候符号和数字混在一起,怎么实现输入?
好吧其实没有关系......一个char数组就搞定了
为了区分符号和数字(以下)

  1. void judge(linklist* numnode,linklist *snode,char x){
  2. if(x=='+'||x=='-'||x=='*'||x=='/'){
  3. push(snode,x);
  4. }
  5. else{
  6. push(numnode,x);
  7. }
  8. return;
  9. }
  10. void ergodicAll(linklist* numnode,linklist *snode,char array[],int len){
  11. for(int i=0;i<len;i++){
  12. judge(numnode,snode,array[i]);
  13. }
  14. return;
  15. }
  16. void ergodic(linklist *numnode){
  17. while(!isEmpty(numnode)){
  18. printf("%d",numnode->data);
  19. numnode=numnode->next;
  20. }
  21. return;
  22. }
  23. void ergodic2(linklist *s){
  24. while(!isEmpty(s)){
  25. printf("%c",s->data);
  26. s=s->next;
  27. }
  28. return;
  29. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注