题目:
题解:
- 按照题意构造链表
- 遍历链表删除指定字符
public String removeFromLinked(String string) {
LinkedList<String> linkedList = new LinkedList<>();
String[] strings = string.split(" ");
String firstNode = strings[1];
linkedList.addFirst(firstNode);
for (int i = 2; i < strings.length - 1 ;) {
String value1 = strings[i];
String value2 = strings[i+1];
instLinked(linkedList, value1, value2);
i = i + 2;
}
String deleteValue = strings[strings.length - 1];
linkedList.removeIf(integer -> integer.equals(deleteValue));
return String.join(" ", linkedList);
}
private void instLinked(LinkedList<String> linkedList, String value1, String value2) {
int i;
for (i = 0; i < linkedList.size(); i++) {
if (linkedList.get(i).equals(value2)) {
break;
}
}
linkedList.add(i+1, value1);
}
时间复杂度:O(n)