import
java.io.*;
import
java.util.*;
class
Node {
int
val;
Node next;
Node(
int
x) {
val = x;
next =
null
;
}
}
public
class
GFG {
public
static
String concatenateList(Node head) {
StringBuilder result =
new
StringBuilder();
Node current = head;
while
(current !=
null
) {
result.append(current.val);
current = current.next;
}
return
result.toString();
}
public
static
void
computePrefixTable(String pattern,
int
[] prefixTable) {
int
m = pattern.length();
int
j =
0
;
prefixTable[
0
] =
0
;
for
(
int
i =
1
; i < m; i++) {
while
(j >
0
&& pattern.charAt(j) != pattern.charAt(i)) {
j = prefixTable[j -
1
];
}
if
(pattern.charAt(j) == pattern.charAt(i)) {
j++;
}
prefixTable[i] = j;
}
}
public
static
int
countOccurrences(Node head1, Node head2) {
String text = concatenateList(head1);
String pattern = concatenateList(head2);
int
n = text.length();
int
m = pattern.length();
if
(m ==
0
) {
return
0
;
}
int
[] prefixTable =
new
int
[m];
computePrefixTable(pattern, prefixTable);
int
count =
0
;
int
i =
0
;
int
j =
0
;
while
(i < n) {
if
(text.charAt(i) == pattern.charAt(j)) {
i++;
j++;
if
(j == m) {
count++;
j = prefixTable[j -
1
];
}
}
else
if
(j >
0
) {
j = prefixTable[j -
1
];
}
else
{
i++;
}
}
return
count;
}
public
static
void
main(String[] args) {
Node head1 =
new
Node(
1
);
head1.next =
new
Node(
2
);
head1.next.next =
new
Node(
3
);
head1.next.next.next =
new
Node(
2
);
head1.next.next.next.next =
new
Node(
4
);
head1.next.next.next.next.next =
new
Node(
5
);
head1.next.next.next.next.next.next =
new
Node(
2
);
head1.next.next.next.next.next.next.next =
new
Node(
4
);
Node head2 =
new
Node(
2
);
head2.next =
new
Node(
4
);
int
result = countOccurrences(head1, head2);
System.out.println(
"Occurrences of head2 in head1: "
+ result);
}
}