import
java.util.Arrays;
public
class
Main {
static
class
Node {
char
data;
Node next;
}
static
void
printLongestCommonPrefix(Node head)
{
if
(head ==
null
) {
System.out.println(
"There is no common prefix"
);
return
;
}
System.out.print(
"The longest common prefix is "
);
while
(head !=
null
) {
System.out.print(head.data);
head = head.next;
}
System.out.println();
}
static
void
initialise(Node[] head, String str)
{
int
l = str.length();
for
(
int
i = l -
1
; i >=
0
; i--) {
Node temp =
new
Node();
temp.data = str.charAt(i);
temp.next = head[
0
];
head[
0
] = temp;
}
}
static
void
deleteNodes(Node head)
{
Node current = head;
Node next;
while
(current !=
null
) {
next = current.next;
current =
null
;
current = next;
}
}
static
void
longestCommonPrefix(Node[] head, String str)
{
int
i =
0
;
Node temp = head[
0
];
Node prev = head[
0
];
while
(temp !=
null
) {
if
(i == str.length() || temp.data != str.charAt(i)) {
if
(temp == head[
0
]) {
head[
0
] =
null
;
}
else
{
prev.next =
null
;
deleteNodes(temp);
}
break
;
}
prev = temp;
temp = temp.next;
i++;
}
}
public
static
void
main(String[] args)
{
String[] arr = {
"geeksforgeeks"
,
"geeks"
,
"geek"
,
"geezer"
,
"geekathon"
};
int
n = arr.length;
Node[] head =
new
Node[
1
];
initialise(head, arr[
0
]);
for
(
int
i =
1
; i < n; i++) {
longestCommonPrefix(head, arr[i]);
}
printLongestCommonPrefix(head[
0
]);
}
}