Advertisement
Alexxik

Untitled

Oct 2nd, 2023
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.03 KB | None | 0 0
  1. // MARK: - Пересечение 2х связанных списков
  2.  
  3. func getIntersectionNode(_ headA: ListNode?, _ headB: ListNode?) -> ListNode? {
  4.         let lengthA = lengthOfList(head: headA)
  5.         let lengthB = lengthOfList(head: headB)
  6.  
  7.         var nodeA = headA
  8.         var nodeB = headB
  9.  
  10.         if lengthA > lengthB {
  11.             for _ in 0..<(lengthA-lengthB) {
  12.                 nodeA = nodeA?.next
  13.             }
  14.         } else if lengthB > lengthA {
  15.             for _ in 0..<(lengthB-lengthA) {
  16.                 nodeB = nodeB?.next
  17.             }
  18.         }
  19.  
  20.         while nodeA != nil {
  21.             if nodeA === nodeB {
  22.                 return nodeA
  23.             }
  24.             nodeA = nodeA?.next
  25.             nodeB = nodeB?.next
  26.         }
  27.         return nil
  28.     }
  29.  
  30.     private func lengthOfList(head: ListNode?) -> Int {
  31.         var length = 0
  32.         var nextNode = head
  33.         while let node = nextNode {
  34.             length += 1
  35.             nextNode = node.next
  36.         }
  37.         return length  
  38.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement