File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments