[Leetcode solution] 160 _ intersection linked list

Source: Internet
Author: User

Directory

  • 160 _ intersection linked list
    • Description
    • Solution 1: hash table
      • Ideas
      • JAVA Implementation
      • Python implementation
    • Solution 2: Double pointer (recommended)
      • Ideas
      • JAVA Implementation
      • Python implementation
160 _ intersection linked list description

Write a program to find the starting node of the intersection of two single-chain tables.

For example, the following two linked lists:

A:          a1 → a2                                        c1 → c2 → c3                               B:     b1 → b2 → b3

The intersection starts at node C1.

Note:

  • If there is no intersection between two linked lists, returnnull.
  • After the returned results, the two linked lists must maintain the original structure.
  • It can be assumed that there is no loop in the entire linked list structure.
  • The program tries its best to meet O (N) Time complexity, and only use o (1) Memory.

Thank you:
Special thanks to @ stellari for adding this issue and creating all test cases.

Solution 1: Hash Table ideas

First, all nodes in Table A are traversed and each node is referenced in a hash table. Next, for each node in the traversal chain table B, if a node reference exists in the hash table, the reference of the node is returned. If no such node is found after traversing all nodes in the Linked List B, returnsnull.

JAVA Implementation
/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {        if (headA == null || headB == null) {            return null;        }                Set<ListNode> nodes = new HashSet<>();        ListNode temp = headA;        while (temp != null) {            nodes.add(temp);            temp = temp.next;        }                temp = headB;        while (temp != null) {            if (nodes.contains(temp)) {                return temp;            }            temp = temp.next;        }        return null;    }}

Complexity Analysis:

  • Time Complexity: \ (O (m + n) \), where \ (M \) represents the number of nodes in linked list A, \ (n \) represents the number of nodes in linked list B, in the worst case, we need to traverse all the nodes in two linked lists.
  • Space complexity: \ (O (m) \) or \ (O (n )\)
Python implementation
# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def getIntersectionNode(self, headA, headB):        """        :type head1, head1: ListNode        :rtype: ListNode        """        if not headA or not headB:            return None                nodesA = set()        curr = headA        while curr:            nodesA.add(curr)            curr = curr.next                    curr = headB        while curr:            if curr in nodesA:                return curr            curr = curr.next        return None

Complexity analysis is the same as above.

Solution 2: Double pointer (recommended)

As the name implies, the dual-pointer solution requires two pointers.pAAndpBPoint to the head node of the linked list A and linked list B respectively, and the next two pointers traverse to the end of the linked list at a step of 1. When the pointerpAWhen traversing to the End Node of linked listpAPoint to the head of linked list B. Similarly, when the pointerpBWhen traversing to the End Node of linked list BpBPoint to the head of linked list. When two pointers meetpAOrpBThe directed node is the intersection node of two linked lists.

To illustrate the two-pointer solution, assume that the structure of linked list A and linked list B is shown in,

The linked list A contains six nodes with values of 1, 3, 5, 7, 9, and 11 respectively. The linked list B contains four nodes, the node values are 2, 4, 9, and 11 respectively. Therefore, the intersection nodes of the two linked lists are 9. Set the length of the non-Intersecting part (that is, the node of the blue part) in linked list A to \ (L1 \), and the non-Intersecting part (that is, the node of the yellow part) in linked list B) the length is \ (L2 \), and the intersection of two linked lists (nodes in red) is \ (L3 \).

As shown in, when the pointerpBPointer when traversing to the End Node 11 of linked list BpATraverse to node 7 in linked list A, next traversal pointerpBIt will be in the position of Node 1 of linked list.

Similarly, when the pointerpAWhen traversing to the End Node 11 of linked list A, the pointerpBIn the position of Node 3 in linked list A, next traversal pointerpAIt will be at Node 2 of linked list B.

After two traversal, the pointerpAThe pointer is located at node 4 in linked list B.pBIt will also reach the position of node 4 in the linked list A. the next traversal of the two pointers will encounter at node 9 (that is, the intersection node. At this time, the length of the two pointers is \ (l1 + l2 + l3 \). The reason is that we can regard the distance between the two pointers as three parts, namely the blue part, the red part, and the orange part, the sequence of the two pointers passing through three parts is different.pAFirst, the blue part and the pointerpBThe first part is orange, but after the first three parts, the length of the two pointers must be the same, so the two pointers will certainly meet each other in the next traversal.

JAVA Implementation
/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {        if (headA == null || headB == null) {            return null;        }                ListNode pA = headA;        ListNode pB = headB;        while (pA != pB) {            pA = pA == null ? headB : pA.next;            pB = pB == null ? headA : pB.next;        }        return pA;    }}

Complexity Analysis:

  • Time Complexity: \ (O (l1 + l2 + l3) = O (n) \). If the two linked lists have intersection nodes, it goes through \ (l1 + l2 + l3 \) after the "length" of, the two pointers will certainly meet
  • Space complexity: \ (O (1) \). You only need to save two references.
Python implementation
# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def getIntersectionNode(self, headA, headB):        """        :type head1, head1: ListNode        :rtype: ListNode        """        if not headA or not headB:            return None                p_a, p_b = headA, headB        while p_a != p_b:            if p_a:                p_a = p_a.next            else:                p_a = headB                        if p_b:                p_b = p_b.next            else:                p_b = headA        return p_a

Complexity analysis is the same as above.

[Leetcode solution] 160 _ intersection linked list

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.