Skip to main content

Evaluate postfix expression using stack in ruby

Ruby program for Evaluate postfix expression using stack. Here more information.

#  Ruby program for 
#  Evaluate postfix expression

#  Stack Node
class StackNode 
	# Define the accessor and reader of class StackNode
	attr_reader :operand, :next
	attr_accessor :operand, :next
	def initialize(operand, top) 
		self.operand = operand
		self.next = top
	end

end

class MyStack 
	# Define the accessor and reader of class MyStack
	attr_reader :top, :count
	attr_accessor :top, :count
	def initialize() 
		self.top = nil
		self.count = 0
	end

	#  Returns the number of element in stack
	def isSize() 
		return self.count
	end

	def isEmpty() 
		if (self.isSize() > 0) 
			return false
		else
 
			return true
		end

	end

	#  Add a new element in stack
	def push(value) 
		#  Make a new stack node
		#  And set as top
		self.top = StackNode.new(value, self.top)
		#  Increase node value
		self.count += 1
	end

	#  Remove a top element 
	def pop() 
		value = self.peek()
		if (self.isEmpty() == false) 
			self.top = self.top.next
			#  Reduce the size
			self.count -= 1
		end

		return value
	end

	#  Used to get top element of stack
	def peek() 
		if (!self.isEmpty()) 
			return self.top.operand
		else
			return 0
		end

	end

end

class Execution 
	def evaluate(e) 
		#  Get the length of expression
		size = e.length
		a = 0
		b = 0
		s = MyStack.new()
		isVaild = true
		i = 0
		#  work with (+,-,/,*,%) operator
		while (i < size && isVaild) 
			if (e[i] >= '0' && e[i] <= '9') 
				a = e[i].ord - '0'.ord
				s.push(a)
			elsif(s.isSize() > 1) 
				a = s.pop()
				b = s.pop()
				#  Perform arithmetic operations between 2 operands
				if (e[i] == '+') 
					s.push(b + a)
				elsif(e[i] == '-') 
					s.push(b - a)
				elsif(e[i] == '*') 
					s.push(b * a)
				elsif(e[i] == '/') 
					s.push(b / a)
				elsif(e[i] == '%') 
					s.push(b % a)
				else
					#  When use other operator
					isVaild = false
				end

			elsif(s.isSize() == 1) 
				#  Special case  
				#  When use +, - at the beginning
				if (e[i] == '-') 
					a = s.pop()
					s.push(-a)
				elsif(e[i] != '+') 
					#  When not use  +,-
					isVaild = false
				end

			else
 
				isVaild = false
			end

			i += 1
		end

		if (isVaild == false) 
			#  Possible case use other operators
			#  1) When using special operators
			#  2) Or expression is invalid
			print(e ," Invalid expression \n")
			return
		end

		print(e ," = ", s.pop(), "\n")
	end

end

def main() 
	task = Execution.new()
	#  Execute the following expression
	#  (1+2)*(3+5)
	task.evaluate("12+35+*")
	#  -((7*2) + (6/2) + 4)
	task.evaluate("72*62/+4+-")
end

main()

Output

12+35+* = 24
72*62/+4+- = -21




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment