NYUer | LeetCode160 Intersection of Two Linked Lists

LeetCode160 Intersection of Two Linked Lists


Author: Stefan Su
Create time: 2022-10-29 01:08:18
Location: New York City, NY, USA

Description Easy

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.
Example 1

在这里插入图片描述

Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
Output: Intersected at '8'
Explanation: The intersected node's value is 8 (note that this must not be 0 if the two 
lists intersect).
From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. 
There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected 
node in B.

- Note that the intersected node's value is not 1 because the nodes with value 1 in A and B 
(2nd node in A and 3rd node in B) are different node references. In other words, they point 
to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A 
and 4th node in B) point to the same location in memory.
Example 2

在这里插入图片描述

Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
Output: Intersected at '2'
Explanation: The intersected node's value is 2 (note that this must not be 0 if 
the two lists intersect).
From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. 
There are 3 nodes before the intersected node in A; There are 1 node before the 
intersected node in B.
Example 3

在这里插入图片描述

Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
Output: No intersection
Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. 
Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB 
can be arbitrary values.
Explanation: The two lists do not intersect, so return null.
Constrains
  • The number of nodes of listA is in the m.
  • The number of nodes of listB is in the n.
  • 1 <= m, n <= 3 * 104
  • 1 <= Node.val <= 105
  • 0 <= skipA < m
  • 0 <= skipB < n
  • intersectVal is 0 if listA and listB do not intersect.
  • intersectVal == listA[skipA] == listB[skipB] if listA and listB intersect.

Analysis

  1. Use two pointers to indicate headA and headB.
  2. Calculate the length of A and B, and compute the diff of length between two linked lists.
  3. Right align two linked lists by moving pointer of the longer linked list diff steps.
  4. Check the remained linked list same or not curA == curB, if yes, return either of curA or curB since the head of them is same. If no, move both ahead to next node. Keep looping until one of linked list is pointing a null pointer, it returns None.

Solution

  • Two pointers version
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        curA, curB = headA, headB
        length_A, length_B = 0, 0
        # get length of each list
        while headA != None:
            headA = headA.next
            length_A += 1
        while headB != None:
            headB = headB.next
            length_B += 1

        # calculate the difference of length_A and length_B
        diff = length_A - length_B
        print(diff)

        # move pointer until the end of two lists is align
        if diff >= 0:
            for _ in range(diff):
                curA = curA.next
        else:
            for _ in range(-diff):
                curB = curB.next

        while curA != None:
            if curA == curB: # key: not curA.val == curB.val
                return curA  # return the head of this linked list
            curA = curA.next
            curB = curB.next

        return None

Advance

For python, there is a smarter version.

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        """
        根据快慢法则,走的快的一定会追上走得慢的。
        在这道题里,有的链表短,他走完了就去走另一条链表,我们可以理解为走的快的指针。

        那么,只要其中一个链表走完了,就去走另一条链表的路。如果有交点,他们最终一定会在同一个
        位置相遇
        """
        if headA is None or headB is None: 
            return None
        cur_a, cur_b = headA, headB     # 用两个指针代替a和b

        while cur_a != cur_b:
            cur_a = cur_a.next if cur_a else headB      # 如果a走完了,那么就切换到b走
            cur_b = cur_b.next if cur_b else headA      # 同理,b走完了就切换到a

        return cur_a

Hopefully, this blog can inspire you when solving LeetCode160. For any questions, please comment below.

猜你喜欢

转载自blog.csdn.net/Moses_SU/article/details/127585893