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