Given two singly linked lists that intersect at some point, find the intersecting node. The lists are non-cyclical.
For example, given A = 3 -> 7 -> 8 -> 10 and B = 99 -> 1 -> 8 -> 10, return the node with value 8.
Example:
Input: l1: 3->7->8->10->NULL, l2: 99->1->8->10
Output: Intersected at 8
Approach
C++
#include <bits/stdc++.h>using namespace std;struct ListNode{int val;ListNode *next;ListNode(int data){this->val = data;this->next = NULL;}};void linkedListTraversal(ListNode *node){while (node != NULL){cout << node->val << " ";node = node->next;}}//function to find length of linked listint linkedListLength(ListNode *node){int length = 0;// iterate untill end of listwhile (node != NULL){node = node->next;length++;}return length;}//function to check intersection point//of two linked listListNode *getIntersectionNode(ListNode *headA, ListNode *headB){if (headA == NULL || headB == NULL){return NULL;}// find length of both listint lenA = linkedListLength(headA);int lenB = linkedListLength(headB);// if first is greater then second// then skipif (lenA > lenB){int diff = lenA - lenB;while (diff > 0){diff--;headA = headA->next;}// if second is greater then second// then skip}else if (lenA < lenB){int diff = lenB - lenA;while (diff > 0){diff--;headB = headB->next;}}// find intersection in both listwhile (headA != NULL){// if intersection found the returnif (headA == headB){return headA;}headA = headA->next;headB = headB->next;}return headA;}int main(){// create two listListNode *l1, *l2;// first list add two node which is differentl1 = new ListNode(3);l1->next = new ListNode(7);// second list add two node which is differentl2 = new ListNode(99);l2->next = new ListNode(1);// for intersection create command node// and assign to both listListNode *n8 = new ListNode(8);l1->next->next = n8;l2->next->next = n8;ListNode *n4 = new ListNode(10);l1->next->next->next = n4;l2->next->next->next = n4;ListNode *isectionNode = getIntersectionNode(l1, l2);cout << "Intersected at " << isectionNode->val;return 0;}
No comments:
Post a Comment