見出し画像

ほぼ日刊競プロ leetcode 160. Intersection of Two Linked Lists

160. 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.
For example, the following two linked lists begin to intersect at node c1:
省略
The test cases are generated such that there are no cycles anywhere in the entire linked structure.
Note that the linked lists must retain their original structure after the function returns.
Custom Judge:
The inputs to the judge are given as follows (your program is not given these inputs):
intersectVal - The value of the node where the intersection occurs. This is 0 if there is no intersected node.
listA - The first linked list.
listB - The second linked list.
skipA - The number of nodes to skip ahead in listA (starting from the head) to get to the intersected node.
skipB - The number of nodes to skip ahead in listB (starting from the head) to get to the intersected node.
The judge will then create the linked structure based on these inputs and pass the two heads, headA and headB to your program. If you correctly return the intersected node, then your solution will be accepted.


考えたこと

二つの連結リストが与えられるので,交差するノードを返すという問題.while文でnextのノードのを取得し,もう一個のノードと確かめる.というものを判定する.ただしheadがNoneとなった場合はもう一つのノードのheadから検索をかける形にする.

ゼロから始めるLeetCode Day35「160. Intersection of Two Linked Lists」
上記に記述してあるように最初のパターンだと時間制限に引っかかってしまう.(なぜ?)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
   def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
       if not headA:
           return None
       elif  not headB:
           return None
       
       LNA = headA
       LNB = headB
       while LNA != LNB:
           LNA = headB if not LNA else LNA.next
           LNB = headA if not LNB else LNB.next
       return LNA

いいなと思ったら応援しよう!