【Hackerrank】Find the merge point of two joined linked lists

You’re given the pointer to the head nodes of two linked lists that merge together at some node. Find the node at which this merger happens. The two head nodes will be different and neither will be NULL.

Input Format
You have to complete the int FindMergeNode(Node* headA, Node* headB) method which takes two arguments - the heads of the linked lists. You should NOT read any input from stdin/console.

Output Format
Find the node at which both lists merge and return the data of that node. Do NOT print anything to stdout/console.

Sample Input

1 --> 2 --> 3 --> NULL
      ^
      |
1-----                           

1 --> 2 --> 3 --> NULL
            ^
            |
      1-----                           

Sample Output

2
3

Explanation
1. As shown in the Input, 2 is the merge point.
2. Similarly 3 is merging point


c++ code :

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
using namespace std;
struct Node
{
	int data;
	Node* next;
};/*
   Find merge point of two linked lists
   Node is defined as
   struct Node
   {
       int data;
       Node* next;
   }
*/
#include <stack>
int FindMergeNode(Node *headA, Node *headB)
{
    // Complete this function
    // Do not write the main method. 
    stack<Node *> sta, stb;
    if(headA == NULL || headB == NULL)
        return 0;
    Node *cur = headA;
    while(cur != NULL)
    {
        sta.push(cur);
        cur = cur->next;
    }
    cur = headB;
    while(cur != NULL)
    {
        stb.push(cur);
        cur = cur->next;
    }
    int last = 0;
    while(!sta.empty() && !stb.empty())
    {
        Node *pa = sta.top();
        Node *pb = stb.top();
        sta.pop();
        stb.pop();
        if(pa->data != pb->data)
        {
            break;
        }
        else last = pa->data;
    }
    return last;
}int main()
{
	Node *A, *B, *C, *D,*E,*F,*G;
	A = new Node();	B= new Node();  C= new Node(); D = new Node(); E = new Node(); F= new Node();G = new Node();
	A->data = 2; B->data = 4; C->data = 3; D->data = 5; E->data = 7; F->data = 6;G->data = 11;

	// case 1 = 
	A->next = B; B->next = C; C->next = D; D->next = E; E->next = NULL;
	F->next = G; G->next = C;
	cout<<FindMergeNode(A,F)<<"\n";
	//case 2.
	A->next = B; B->next = C; C->next = E;  E->next = NULL;
	F->next = G; G->next = D;D->next = C;
	cout<<FindMergeNode(A,F)<<"\n";
	//case 3:
	A->next = B; B->next = E; E->next = NULL;
	F->next = G; G->next = D;D->next = C; C->next = E;
	cout<<FindMergeNode(A,F)<<"\n";
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值