forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0150-evaluate-reverse-polish-notation.swift
58 lines (50 loc) · 1.25 KB
/
0150-evaluate-reverse-polish-notation.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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
}
}