티스토리 뷰

문제 설명

제한 조건

https://leetcode.com/problems/intersection-of-two-linked-lists/description/

 

Intersection of Two Linked Lists - LeetCode

Can you solve this real interview question? Intersection of Two Linked Lists - Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null. F

leetcode.com

내 답안

/**
 * 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? {

        if headA == nil || headB == nil {
            return nil
        }
    
    var a = headA
    var b = headB
    
    while a !== b {
        a = a == nil ? headB : a?.next
        b = b == nil ? headA : b?.next
    }
    
    return a
        
    }
}

접근 방법

다른 풀이

알게 된 것

최근에 올라온 글