-
Notifications
You must be signed in to change notification settings - Fork 25
/
Merge two linked list
139 lines (116 loc) · 1.94 KB
/
Merge two linked list
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include<iostream>
using namespace std;
struct node
{
int data;
node *next;
};
node *head1=NULL;
node *head2=NULL;
node* getnode()
{
int data1;
node* newnode=new node;
cout<<"Enter data : ";
cin>>data1;
newnode->data=data1;
newnode->next=NULL;
}
//Create Slinked lidt
node* createlist(node *head,int n)
{
node *newnode,*temp;
for(int i=0;i<n;i++)
{
newnode=getnode();
temp=head;
if(head==NULL)
{
head=newnode;
}
else{
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=newnode;
}
}
cout<<"Elements are Inserted Successfully. "<<endl;
return head;
}
//find length
int length(node *head)
{
node *temp;
int l=0;
temp=head;
if(head==NULL)
{
return 0;
}
else
{
while(temp!=NULL)
{
l++;
temp=temp->next;
}
return l;
}
}
//Displaying linked list
void display(node *head)
{
node *temp;
temp=head;
if(head==NULL)
{
cout<<"Linklist is Empty "<<endl;
}
else
{
cout<<"Linked List Elements Are : "<<endl;
while(temp!=NULL)
{
cout<<temp->data<<" -> ";
temp=temp->next;
}
cout<<endl;
}
}
node* mergepoint(node *head1,node *head2)
{
node *temp;
while(head1!=NULL)
{
temp=head2;
while(temp!=NULL)
{
if(temp->data==head1->data)
{
return head1;
}
temp=temp->next;
}
head1=head1->next;
}
return NULL;
}
int main()
{
int n,k;
cout<<"Enter no. of nodes in 1st List : ";
cin>>n;
node* h1=createlist(head1,n);
cout<<"Enter no. of nodes in 2nd List : ";
cin>>k;
node *h2=createlist(head2,k);
display(h1);
display(h2);
node *ans=mergepoint(h1,h2);
if(ans )
cout<<"Merging point of two list is : "<<ans->data;
else
cout<<"No Merging point ";
}