Skip to content

Commit

Permalink
面试题02.07.链表相交 Swift版本
Browse files Browse the repository at this point in the history
  • Loading branch information
zhangrunzhe committed Oct 21, 2024
1 parent c0c3ebb commit e0c1e2e
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions problems/面试题02.07.链表相交.md
Original file line number Diff line number Diff line change
Expand Up @@ -535,6 +535,45 @@ public ListNode GetIntersectionNode(ListNode headA, ListNode headB)
}
```

### Swift:
```swift
func getIntersectionNode(_ headA: ListNode?, _ headB: ListNode?) -> ListNode? {
var lenA = 0
var lenB = 0
var nodeA = headA
var nodeB = headB
// 计算链表A和链表B的长度
while nodeA != nil {
lenA += 1
nodeA = nodeA?.next
}
while nodeB != nil {
lenB += 1
nodeB = nodeB?.next
}
// 重置指针
nodeA = headA
nodeB = headB
// 如果链表A更长,让它先走lenA-lenB步
if lenA > lenB {
for _ in 0..<(lenA - lenB) {
nodeA = nodeA?.next
}
} else if lenB > lenA {
// 如果链表B更长,让它先走lenB-lenA步
for _ in 0..<(lenB - lenA) {
nodeB = nodeB?.next
}
}
// 同时遍历两个链表,寻找交点
while nodeA !== nodeB {
nodeA = nodeA?.next
nodeB = nodeB?.next
}
return nodeA
}
```


<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
Expand Down

0 comments on commit e0c1e2e

Please sign in to comment.