Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[pull] master from youngyangyang04:master #500

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
pull merged 6 commits into AlgorithmAndLeetCode:master from youngyangyang04:master
Nov 27, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
面试题02.07.链表相交 Swift版本
  • Loading branch information
zhangrunzhe committed Oct 21, 2024
commit e0c1e2e31784dfb13ea8f710ff216bcdccf5d3bf
39 changes: 39 additions & 0 deletions problems/面试题02.07.链表相交.md
View file Open in desktop
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

AltStyle によって変換されたページ (->オリジナル) /