-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path138-copy-list-with-random-pointer.swift
62 lines (57 loc) · 1.34 KB
/
138-copy-list-with-random-pointer.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
59
60
61
62
/**
* Definition for a Node.
* public class Node {
* public var val: Int
* public var next: Node?
* public var random: Node?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* self.random = nil
* }
* }
*/
extension Node {
var copy: Node {
var x = Node(val)
x.next = next
return x
}
}
class Solution {
// Time O(n)
// Space O(n)
func copyRandomList(_ head: Node?) -> Node? {
interveawe(head)
linkRandoms(head)
return filterCopy(head)
}
func interveawe(_ head: Node?) {
var curr = head
while curr != nil {
let oldNext = curr?.next
curr?.next = curr?.copy
curr?.next?.next = oldNext
curr = oldNext
}
}
func linkRandoms(_ head: Node?) {
var curr = head
while curr != nil {
curr?.next?.random = curr?.random?.next
curr = curr?.next?.next
}
}
func filterCopy(_ head: Node?) -> Node? {
var result = head?.next
var curr = head
while curr != nil {
let copy = curr?.next
let next = curr?.next?.next
copy?.next = next?.next
curr?.next = next
curr = next
}
return result
}
}