Skip to content

Commit 48d642f

Browse files
committed
Swift implementation for LCOF 52
1 parent 684d3e9 commit 48d642f

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

lcof/面试题52. 两个链表的第一个公共节点/README.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,34 @@ public class Solution {
253253
}
254254
```
255255

256+
#### Swift
257+
258+
```swift
259+
/* public class ListNode {
260+
* public var val: Int
261+
* public var next: ListNode?
262+
* public init(_ val: Int) {
263+
* self.val = val
264+
* self.next = nil
265+
* }
266+
* }
267+
*/
268+
269+
class Solution {
270+
func getIntersectionNode(_ headA: ListNode?, _ headB: ListNode?) -> ListNode? {
271+
var a = headA
272+
var b = headB
273+
274+
while a !== b {
275+
a = a == nil ? headB : a?.next
276+
b = b == nil ? headA : b?.next
277+
}
278+
279+
return a
280+
}
281+
}
282+
```
283+
256284
<!-- tabs:end -->
257285

258286
<!-- solution:end -->
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/* public class ListNode {
2+
* public var val: Int
3+
* public var next: ListNode?
4+
* public init(_ val: Int) {
5+
* self.val = val
6+
* self.next = nil
7+
* }
8+
* }
9+
*/
10+
11+
class Solution {
12+
func getIntersectionNode(_ headA: ListNode?, _ headB: ListNode?) -> ListNode? {
13+
var a = headA
14+
var b = headB
15+
16+
while a !== b {
17+
a = a == nil ? headB : a?.next
18+
b = b == nil ? headA : b?.next
19+
}
20+
21+
return a
22+
}
23+
}

0 commit comments

Comments
 (0)