Skip to content

Commit 3fcd994

Browse files
authored
Merge pull request neetcode-gh#615 from diss1993/ticket/150
Swift | 150. Evaluate Reverse Polish Notation
2 parents 0aa5207 + 7eb4a14 commit 3fcd994

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
class Solution {
2+
func evalRPN(_ tokens: [String]) -> Int {
3+
guard tokens.count > 0 else { return 0 }
4+
var stack: Stack<Int> = Stack()
5+
for c in tokens {
6+
if c == "+" {
7+
stack.push((stack.pop() ?? 0) + (stack.pop() ?? 0) )
8+
} else if c == "-" {
9+
var a = stack.pop() ?? 0
10+
var b = stack.pop() ?? 0
11+
stack.push(b - a)
12+
} else if c == "*" {
13+
stack.push((stack.pop() ?? 0) * (stack.pop() ?? 0) )
14+
} else if c == "/" {
15+
var a = stack.pop() ?? 0
16+
var b = stack.pop() ?? 0
17+
stack.push(b / a)
18+
} else {
19+
stack.push(Int(c) ?? 0)
20+
}
21+
}
22+
return stack.pop() ?? 0
23+
}
24+
}
25+
26+
class Node<T> {
27+
var data: T
28+
var next: Node<T>?
29+
init(_ value: T) {
30+
self.data = value
31+
}
32+
}
33+
34+
class Stack<T> {
35+
36+
var head: Node<T>?
37+
38+
var isEmpty: Bool {
39+
head == nil
40+
}
41+
42+
func peak() -> Node<T>? {
43+
head
44+
}
45+
46+
func push(_ data: T) {
47+
var node = Node<T>(data)
48+
node.next = head
49+
head = node
50+
}
51+
52+
func pop() -> T? {
53+
var data = head?.data
54+
head = head?.next
55+
return data
56+
}
57+
58+
}

0 commit comments

Comments
 (0)