Intersection of Linked Lists
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.
Notes:
- If The linked lists has no intersection at all, return
null
.
- The linked lists must retain their original structure after the function returns.
- You may assume there is no cycles anywhere in the entire linked structure.
- Your code should preferably run in O (n) time and use only O (1) memory.
Find the node at the intersection of the two linked lists. If you do not want to, return null.
if the two linked lists intersect, the second half of them must be the same. The second half of the two linked lists are aligned, that is, the long list goes back, until it starts traversing the two linked lists, just like the short list length, and the first node found is the node at the intersection. C + +
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * listnode (int x): Val (x), Next (NULL) {} *}; */class Soluti On {public: listnode *getintersectionnode (ListNode *heada, ListNode *headb) { int nA = 0,NB = 0,n;//linked list length list node* p; p = Heada; The length of the Heada NA while (p) { na++; p = p->next; } p = headb; The length of the headb NB while (p) { nb++; p = p->next; } if (NA < NB) { n = nb-na; while (n--) headb = headb->next; } else if (NA > NB) { n = na-nb; while (n--) Heada = heada->next; } while (Heada && headb) { if (Heada = = headb) return heada; Heada = heada->next; HEADB = headb->next; } return NULL; }};
python
# Definition for singly-linked list.# class listnode:# def __init__ (self, x): # self.val = x# Self.next = Nonec Lass Solution: # @param the listnodes # @return The intersected ListNode def getintersectionnode (self, Heada , headb): na = NB = 0 p = heada while (P was not None): na = Na + 1 p = p.next p = headb WH Ile (P isn't None): nb = nb + 1 p = p.next if (NA < NB): n = nb-na while (n): headb = Headb.next n = n-1 elif (NA > NB): n = na-nb while (n): Heada = heada.next n = n -1 while (Heada and headb): if (Heada = = headb): return heada heada = heada.next headb = Headb.next return None
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode-160-intersection of Linked Lists