Title: https://oj.leetcode.com/problems/intersection-of-two-linked-lists/
Write a program of the node at which the intersection of two singly linked lists.
For example, the following two linked lists:
A: a1→a2
↘
c1→c2→c3
↗
B: b1→b2→b3
Begin to intersect at node C1.
Notes:if The two linked lists have no intersection at all, return null. The linked lists must retain their original after the function structure. You could assume there are no cycles anywhere in the entire linked. Your code should preferably run in O (n) time and with only O (1) memory. Analysis:
If one of the linked lists is empty, returns NULL, first traversing the list to get the length of a, B, or null if the last node is different, leaving the long list with the length difference, and then walking back together until the node returns the same.
C + + implementation:
/** * Definition for singly-linked list.
* struct ListNode {* int val;
* ListNode *next;
* ListNode (int x): Val (x), Next (NULL) {} *}; * * Class Solution {public:listnode *getintersectionnode (ListNode *heada, ListNode *headb) {if (Heada = NULL ||
HEADB = = null) {return null;
int LenA = 1;
ListNode *ha = Heada;
while (Ha->next!= NULL) {++lena;
HA = ha->next;
int LenB = 1;
ListNode *HB = headb;
while (Hb->next!= NULL) {++lenb;
HB = hb->next;
} if (HA!= HB) {return NULL;
HA = Heada;
HB = headb; if (LenA > LenB) {for (int i = 0; i < Lena-lenb ++i) {HA = Ha->
; next; } else {fort i = 0; i < Lenb-lena;
++i) {HB = hb->next;
} while (ha!= hB) {ha = ha->next;
HB = hb->next;
} return HA; }
};
Python implementations:
# Definition for singly-linked list. # class ListNode: # def __init__ (self, x): # self.val = x # self.next = None class Solution: # @p Aram Two Listnodes # @return the intersected ListNode def getintersectionnode (self, Heada, headb): If head A = = None or headb = None:return None LenA = 1 HA = Heada while Ha.next!= None:lena + + 1 HA = Ha.next LenB = 1 HB = headb while Hb.nex
T!= None:lenb + + 1 HB = Hb.next if HA!= hb:return None HA = Heada HB = headb if LenA > Lenb:for i in Range (LENA-LENB): H A = Ha.next else:for i in Range (Lenb-lena): HB = Hb.next while HA
!= Hb:ha = Ha.next HB = hb.next return HA