infix2rpn
还是上一次csc2100作业的题目,中缀式转化为后缀式,不讨论算法的问题,因为题目里面提供了…… 仅仅用来练习stack 和 queue的使用。 确实认真编了,甚至写了点注释……我的不好习惯——一直以来不喜欢写注释。 今天在ul看了看ruby in a nutshell,决定用这个来写试试,结果发现……竟然才那么几行就搞定了…… def isOperator(op) return 3 if op == '^' return 2 if op == '*' || op == '/' return 1 if op == '+' || op == '-' return 0 end puts "Input your infix expression:" s=[] q=[] gets.each_byte{ |x| t=x.chr q.push(t) if /[a-z]/ =~ t if (t =~ /[+-*/^]/) !=nil then while isOperator(s.last) >= isOperator(t) do q.push(s.pop) end s.push(t) end s.push(t) if t == '(' if t == ')' then while (ch = s.pop) != '(' && s.size!=0 do q.push(ch) end if ch!='(' puts "Mismatched!" abort end end } while s.size > 0 do q.push(ch=s.pop) if ch=='(' puts "Mismatched!" abort end end puts q.join 果然是…… ruby 啊,貌似原来用 c写的那个,俄,真是长啊。 不过想来,原来那个主要是花了很多工夫在stackADT和queueADT的implementation上。而用ruby又何必要自己去做stack和queue呢?array本来就有那些功能。 array可以 push也可以pop 这样就能当stack用了 而queue的实现也很简单,array的push和shift就可以了。 嗯 再感叹一下oop果然不同凡响 ...