Skip to main content

Evaluate postfix expression using stack in swift

Swift program for Evaluate postfix expression using stack. Here problem description and other solutions.

import Foundation
/* 
    Swift 4 program for 
    Evaluate postfix expression
*/
// Stack Node
class StackNode
{
	var operand: Int;
	var next: StackNode? ;
	init(_ operand: Int, _ top: StackNode? )
	{
		self.operand = operand;
		self.next = top;
	}
}
class MyStack
{
	var top: StackNode? ;
	var count: Int;
	init()
	{
		self.top = nil;
		self.count = 0;
	}
	// Returns the number of element in stack
	func isSize() -> Int
	{
		return self.count;
	}
	func isEmpty() -> Bool
	{
		if (self.isSize() > 0)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	// Add a new element in stack
	func push(_ value: Int)
	{
		// Make a new stack node
		// And set as top
		self.top = StackNode(value, self.top);
		// Increase node value
		self.count += 1;
	}
	// Remove a top element 
	func pop() -> Int
	{
		let value: Int = self.peek();
		if (self.isEmpty() == false)
		{
			self.top = self.top!.next;
			// Reduce the size
			self.count -= 1;
		}
		return value;
	}
	// Used to get top element of stack
	func peek() -> Int
	{
		if (!self.isEmpty())
		{
			return self.top!.operand;
		}
		else
		{
			return 0;
		}
	}
}
class Execution
{
	func evaluate(_ expression: String)
	{
      	let e = Array(expression);
		// Get the length of expression
		let size: Int = e.count;
		var a: Int = 0;
		var b: Int = 0;
		let s: MyStack = MyStack();
		var isVaild: Bool = true;
		var i: Int = 0;
		// work with (+,-,/,*,%) operator
		while (i < size && isVaild)
		{
			if (e[i] >= "0" && e[i] <= "9")
			{
				a = Int(UnicodeScalar(String(e[i]))!.value) -
                  Int(UnicodeScalar(String("0"))!.value);
				s.push(a);
			}
			else if (s.isSize() > 1)
			{
				a = s.pop();
				b = s.pop();
				// Perform arithmetic operations between 2 operands
				if (e[i] == "+")
				{
					s.push(b + a);
				}
				else if (e[i] == "-")
				{
					s.push(b - a);
				}
				else if (e[i] == "*")
				{
					s.push(b * a);
				}
				else if (e[i] == "/")
				{
					s.push(b / a);
				}
				else if (e[i] == "%")
				{
					s.push(b % a);
				}
				else
				{
					// When use other operator
					isVaild = false;
				}
			}
			else if (s.isSize() == 1)
			{
				// Special case  
				// When use +, - at the beginning
				if (e[i] == "-")
				{
					a = s.pop();
					s.push(-a);
				}
				else if (e[i] != "+")
				{
					// When not use  +,-
					isVaild = false;
				}
			}
			else
			{
				isVaild = false;
			}
			i += 1;
		}
		if (isVaild == false)
		{
			// Possible case use other operators
			// 1) When using special operators
			// 2) Or expression is invalid
			print(e + " Invalid expression ");
			return;
		}
		print(expression ," = ",s.pop());
	}
	static func main(_ args: [String])
	{
		let task: Execution = Execution();
		// Execute the following expression
		// (1+2)*(3+5)
		task.evaluate("12+35+*");
		// -((7*2) + (6/2) + 4)
		task.evaluate("72*62/+4+-");
	}
}
Execution.main([String]());

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