在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Write a program to find the node at which the intersection of two singly linked lists begins. For example, the following two linked lists: A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3 begin to intersect at node c1. Notes:
编写一个程序,找到两个单链表相交的起始节点。 例如,下面的两个链表: A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3 在节点 c1 开始相交。 注意:
1 class Solution { 2 func getIntersectionNode(_ headA: ListNode?, _ headB: ListNode? ) -> ListNode? { 3 if headA == nil || headB == nil { 4 return nil 5 } 6 7 var a = headA 8 var b = headB 9 while (a !== b) { 10 if a != nil { 11 a = a?.next 12 } else { 13 a = headB 14 } 15 16 if b != nil { 17 b = b?.next 18 } else { 19 b = headA 20 } 21 } 22 return a 23 } 24 25 public class ListNode: Equatable { 26 27 public var val: Int 28 public var next: ListNode? 29 30 public init(_ val: Int) { 31 self.val = val 32 self.next = nil 33 } 34 35 public static func ==(lhs: Solution.ListNode, rhs: Solution.ListNode) -> Bool { 36 return lhs.val == rhs.val && lhs.next == rhs.next 37 } 38 } 39 }
|
请发表评论