In this Leetcode Intersection of Two Linked Lists problem solution we have Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.
Problem solution in Python.
class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: s1=[] s2=[] while headA is not None: s1.append(headA) headA=headA.next while headB is not None: s2.append(headB) headB=headB.next wow = None while s1 and s2: if s1[-1] == s2.pop(): wow=s1.pop() else: return wow return wow
Problem solution in Java.
public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { int ACount =0; int BCount=0; ListNode A=headA; ListNode B=headB; while(A!=null){ ACount++; A=A.next; } while(B!=null){ BCount++; B=B.next; } int diff= Math.abs(ACount-BCount); A=headA; B=headB; if(ACount>BCount){ while(diff>0){ A=A.next; diff--; } }else{ while(diff>0){ B=B.next; diff--; } } while(A!=B){ A=A.next; B=B.next; } return A; } }
Problem solution in C++.
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { ListNode * a = headA, *b = headB; while(a != NULL && b != NULL) { if(a == b) return a; a = a->next; b = b->next; if(a == NULL && b == NULL) return NULL; if(a == NULL) a = headB; if(b == NULL) b = headA; } return NULL; }
Problem solution in C.
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) { if(headA==NULL && headB==NULL) return NULL; int countA=0; int countB=0; struct ListNode* tmpA=headA; struct ListNode* tmpB=headB; while(tmpA!=NULL || tmpB!=NULL){ if(tmpA!=NULL){countA++;tmpA=tmpA->next;} if(tmpB!=NULL){countB++;tmpB=tmpB->next;} } tmpA=headA; tmpB=headB; int diff; if(countA>=countB){ diff=countA-countB; while(diff){tmpA=tmpA->next;diff--;} } else{ diff=countB-countA; while(diff){tmpB=tmpB->next;diff--;} } while(tmpA!=NULL && tmpB!=NULL){ if(tmpA==tmpB) return tmpA; tmpA=tmpA->next; tmpB=tmpB->next; } return NULL; }
0 Comments