Leetcode "intersection of the Linked Lists" Python implementation

Source: Internet
Author: User

title :

Write a program to find the node at which the intersection of the singly linked lists begins.

For example, the following, linked lists:

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

Begin to intersect at node C1.

code : OJ online test via runtime:1604 ms

1 #Definition for singly-linked list.2 #class ListNode:3 #def __init__ (self, x):4 #self.val = x5 #Self.next = None6 7 classSolution:8     #@param listnodes9     #@return The intersected ListNodeTen     defGetlistlen (self,head): OneLength =0 A          whileHead is  notNone: -Length + = 1 -Head =Head.next the         returnlength -              -     defGetintersectionnode (self, Heada, headb): -         ifHeada isNoneorHeadb isNone: +             returnNone -          +HA =Heada AHB =headb at          -LenA =Self.getlistlen (HA) -LenB =Self.getlistlen (HB) -          -         ifLenA >LenB: -Distance = LenA-LenB in              forIinchRange (0,distance): -HA =Ha.next to         ifLenA <LenB: +Distance = LenB-LenA -              forIinchRange (0,distance): theHB =Hb.next *          $intersection =NonePanax Notoginseng          whileHA is  notNone andHb is  notNone: -             ifHA = =HB: the                 returnHA +             Else: AHA =Ha.next theHB =Hb.next +         returnIntersection

Ideas :

1. First record the length of the two linked list

2. Double pointers to two lists point to the long list first step, get a new linked list table header

3. Compare the values of each pointer of the two list one after the other equal: until the equality is found, or to none

Leetcode "intersection of the Linked Lists" Python implementation

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.