-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathintersection_between_linked_list.java
More file actions
127 lines (122 loc) · 2.52 KB
/
intersection_between_linked_list.java
File metadata and controls
127 lines (122 loc) · 2.52 KB
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
public class FindIntersectionOfLinkedLists {
public LinkedListIntersection a;
public LinkedListIntersection b;
public void createLists(){
a = new LinkedListIntersection();
a.addAtEnd(1);
a.addAtEnd(10);
a.addAtEnd(20);
Node tmp = a.addAtEnd(30);
a.addAtEnd(40);
a.addAtEnd(50);
a.addAtEnd(60);
System.out.print("List A : ");
a.display();
b = new LinkedListIntersection();
b.addAtEnd(5);
b.addAtEnd(15);
b.createIntersection(a,tmp);
System.out.print("List B : ");
b.display();
}
public void findIntersectionByLength(){
int a_len=0;
int b_len=0;
int lenDiff=0;
boolean intsctFound = false;
Node an = a.head;
Node bn = b.head;
while(an!=null){
an=an.next;
a_len++;
}
while(bn!=null){
bn=bn.next;
b_len++;
}
an = a.head;
bn = b.head;
if(a_len>b_len){
lenDiff = a_len-b_len;
while(lenDiff!=0){
an = an.next;
lenDiff--;
}
}else{
lenDiff = b_len-a_len;
while(lenDiff!=0){
bn = bn.next;
lenDiff--;
}
}
while(an!=null && bn!=null){
if(an==bn) {
System.out.print("Intersection found at " + an.data);
intsctFound = true;
break;
}
else{
an = an.next;
bn = bn.next;
}
}
if(intsctFound!=true){
System.out.print("Intersection Not Found");
}
}
public static void main (String[] args) throws java.lang.Exception
{
FindIntersectionOfLinkedLists i = new FindIntersectionOfLinkedLists();
i.createLists();
i.findIntersectionByLength();
}
}
class Node{
public int data;
public Node next;
public Node(int data){
this.data = data;
this.next = null;
}
}
class LinkedListIntersection{
public Node head;
public LinkedListIntersection(){
head=null;
}
public Node addAtEnd(int data){
Node n = new Node(data);
if (head==null){
n.next = head;
head = n;
}
else{
Node currNode = head;
while(currNode.next!=null){
currNode = currNode.next;
}
currNode.next = n;
}
return n;
}
public void createIntersection(LinkedListIntersection a, Node nd){
Node hd = a.head; // this is the list to whcih another list will intersect, in our example its list a
while(hd!=nd){
hd = hd.next;
}
Node currNode = head;// this is for the list which will connect, in our example its list b
while(currNode.next!=null){
currNode = currNode.next;
}
currNode.next = hd; ;
}
public void display(){
System.out.println("");
Node currNode = head;
while(currNode!=null){
System.out.print("->" + currNode.data);
currNode=currNode.next;
}
System.out.println("");
}
}