-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathintersectionofLinkedLists.cpp
100 lines (85 loc) · 2.16 KB
/
intersectionofLinkedLists.cpp
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
// C++ program for intersection of two sorted linked lists
#include<iostream>
using namespace std;
/* Link list node */
struct Node {
int data;
Node* next;
};
void push(Node** head_ref, int new_data);
/*This solution uses the temporary
dummy to build up the result list */
Node* sortedIntersect(Node* a, Node* b)
{
Node dummy;
Node* tail = &dummy;
dummy.next = NULL;
/* Once one or the other
list runs out -- we're done */
while (a != NULL && b != NULL) {
if (a->data == b->data) {
push((&tail->next), a->data);
tail = tail->next;
a = a->next;
b = b->next;
}
/* advance the smaller list */
else if (a->data < b->data)
a = a->next;
else
b = b->next;
}
return (dummy.next);
}
/* UTILITY FUNCTIONS */
/* Function to insert a node at
the beginning of the linked list */
void push(Node** head_ref, int new_data)
{
/* allocate node */
Node* new_node = (Node*)malloc(
sizeof(Node));
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Function to print nodes in
a given linked list */
void printList(Node* node)
{
while (node != NULL) {
cout << node->data <<" ";
node = node->next;
}
}
/* Driver program to test above functions*/
int main()
{
/* Start with the empty lists */
Node* a = NULL;
Node* b = NULL;
Node* intersect = NULL;
/* Let us create the first sorted
linked list to test the functions
Created linked list will be
1->2->3->4->5->6 */
push(&a, 6);
push(&a, 5);
push(&a, 4);
push(&a, 3);
push(&a, 2);
push(&a, 1);
/* Let us create the second sorted linked list
Created linked list will be 2->4->6->8 */
push(&b, 8);
push(&b, 6);
push(&b, 4);
push(&b, 2);
/* Find the intersection two linked lists */
intersect = sortedIntersect(a, b);
cout<<"Linked list containing common items of a & b \n";
printList(intersect);
}