给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/intersection-of-two-linked-lists/
/**
* 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? {
var curA = headA
var curB = headB
/*
思路:A、B同时遍历,若至末尾则从另一条开头处遍历
A: 1->2->3->4->5->nil
B: 7->8->4->5->nil
A->B: 1->2->3->4->5->7->8->4->5->nil
B->A: 7->8->4->5->1->2->3->4->5->nil
^
*/
// 相交则必相等,不相交则末尾nil也必相等, 所以不会死循环
while curA !== curB {
curA = (curA == nil ? headB : curA?.next)
curB = (curB == nil ? headA : curB?.next)
}
return curA
}
}
image.png
网友评论