Skip to content

Commit

Permalink
Merge pull request neetcode-gh#615 from diss1993/ticket/150
Browse files Browse the repository at this point in the history
Swift | 150. Evaluate Reverse Polish Notation
  • Loading branch information
Ahmad-A0 authored Jul 25, 2022
2 parents 0aa5207 + 7eb4a14 commit 3fcd994
Showing 1 changed file with 58 additions and 0 deletions.
58 changes: 58 additions & 0 deletions swift/150-Evaluate-Reverse-Polish-Notation.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
class Solution {
func evalRPN(_ tokens: [String]) -> Int {
guard tokens.count > 0 else { return 0 }
var stack: Stack<Int> = Stack()
for c in tokens {
if c == "+" {
stack.push((stack.pop() ?? 0) + (stack.pop() ?? 0) )
} else if c == "-" {
var a = stack.pop() ?? 0
var b = stack.pop() ?? 0
stack.push(b - a)
} else if c == "*" {
stack.push((stack.pop() ?? 0) * (stack.pop() ?? 0) )
} else if c == "/" {
var a = stack.pop() ?? 0
var b = stack.pop() ?? 0
stack.push(b / a)
} else {
stack.push(Int(c) ?? 0)
}
}
return stack.pop() ?? 0
}
}

class Node<T> {
var data: T
var next: Node<T>?
init(_ value: T) {
self.data = value
}
}

class Stack<T> {

var head: Node<T>?

var isEmpty: Bool {
head == nil
}

func peak() -> Node<T>? {
head
}

func push(_ data: T) {
var node = Node<T>(data)
node.next = head
head = node
}

func pop() -> T? {
var data = head?.data
head = head?.next
return data
}

}

0 comments on commit 3fcd994

Please sign in to comment.