-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path160_intersection_of_two_linkedlist.swift
74 lines (70 loc) · 2.14 KB
/
160_intersection_of_two_linkedlist.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
63
64
65
66
67
68
69
70
71
72
73
74
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* }
* }
*/
class Solution {
func getIntersectionNode(_ headA: ListNode?, _ headB: ListNode?) -> ListNode? {
if let nodeA = headA, let nodeB = headB {
if nodeA === nodeB {
return nodeA
} else {
// compare the depth
var depthA = getListDepth(nodeA)
var depthB = getListDepth(nodeB)
if depthA <= depthB {
let diff = depthB - depthA
print("diff: " + String(diff))
return findIntersection(nodeA, nodeB, diff)
} else {
let diff = depthA - depthB
print("diff: " + String(diff))
return findIntersection(nodeB, nodeA, diff)
}
}
}
return nil
}
func getListDepth(_ head: ListNode?) -> Int {
if var currentNode = head {
var count = 0
while let nextNode = currentNode.next {
count += 1
currentNode = nextNode
}
return count
}
return 0
}
func findIntersection (_ nodeA: ListNode?, _ nodeB: ListNode?, _ diff: Int) -> ListNode? {
if var nextA = nodeA, var nextB = nodeB {
if diff != 0 {
for i in 1...diff {
if let hasNext = nextB.next {
nextB = hasNext
}
}
print("starting value: " + String(nextB.val))
}
while true {
if nextA === nextB {
return nextA
}
if let nonLastB = nextB.next, let nonLastA = nextA.next {
nextB = nonLastB
nextA = nonLastA
continue
} else {
break
}
}
}
return nil
}
}