forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request neetcode-gh#615 from diss1993/ticket/150
Swift | 150. Evaluate Reverse Polish Notation
- Loading branch information
Showing
1 changed file
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
|
||
} |