Не уверен, что кто-то рискнет это осмыслить, но попытка - не пытка.
package com.javarush.task.task22.task2209;
import java.io.*;
import java.util.*;
/*
Составить цепочку слов
*/
public class Solution {
public static void main(String[] args) throws IOException {
ArrayList<String> allWords = new ArrayList<>();
BufferedReader pathReader = new BufferedReader(new InputStreamReader(System.in));
String path = pathReader.readLine();
pathReader.close();
//path = "D:\\test.txt";
BufferedReader br = new BufferedReader(new FileReader(path));
while (br.ready()) {
for (String s : br.readLine().split(" ")) allWords.add(s);
}
br.close();
StringBuilder result = getLine(allWords.toArray(new String[0]));
System.out.println(result.toString());
}
public static StringBuilder getLine(String... words) {
if (words.length == 0) return new StringBuilder();
ArrayList<String> w = new ArrayList<>(Arrays.asList(words));
LL list = new LL();
int i = 0;
int laps = 0;
boolean b;
while (w.size() > 0) {
if (laps > 1) {
insertInto(list, w);
break;
}
if (i == w.size()) {
i = 0;
laps++;
}
b = list.insertWord(w.get(i));
if (b) {
w.remove(i);
laps = 0;
}
else i++;
}
StringBuilder sb = new StringBuilder();
sb.append(list.chain.remove(0));
for (String s : list.chain) sb.append(" " + s);
return sb;
}
private static void insertInto(LL list, ArrayList<String> w) {
LinkedList<String> chainL = list.chain;
char fLetter;
char lLetter;
for (String s : w) {
fLetter = s.charAt(0);
lLetter = s.charAt(s.length() - 1);
for (int i = 0; i < chainL.size() - 1; i++) {
if ((chainL.get(i).charAt(chainL.get(i).length() - 1) + "").equalsIgnoreCase(fLetter + "") &&
(chainL.get(i + 1).charAt(0) + "").equalsIgnoreCase(lLetter + "")) {
chainL.add(i + 1, s);
break;
}
}
}
}
static class LL {
private LinkedList<String> chain = new LinkedList<>();
private char bChar;
private char eChar;
public boolean insertWord(String word) {
if (isEmpty()) {
chain.add(word);
bChar = chain.get(0).charAt(0);
eChar = chain.get(0).charAt(chain.get(0).length() - 1);
return true;
} else {
if ((word.charAt(word.length() - 1) + "").equalsIgnoreCase(bChar + "")) {
insertFirst(word);
return true;
}
else if ((word.charAt(0) + "").equalsIgnoreCase(eChar + "")) {
insertLast(word);
return true;
}
else return false;
}
}
private void insertFirst(String word) {
chain.add(0, word);
bChar = word.charAt(0);
}
private void insertLast(String word) {
chain.add(word);
eChar = word.charAt(word.length() - 1);
}
public boolean isEmpty() {
return chain.size() == 0;
}
}
}