题解 | #从单向链表中删除指定值的节点#
使用linkedList集合,利用迭代器遍历头节点,提高效率。
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextInt()) { // 注意 while 处理多个 case
int n = in.nextInt();
List<Integer> list = new LinkedList<>();
list.add(in.nextInt());
for(int i=0;i<n-1;i++){
int node = in.nextInt();
int position = in.nextInt();
int leng = list.size();
if(i==0){
list.add(node);
}else{
// 利用迭代器遍历linkedList效率高
Iterator<Integer> iter = list.iterator();
int j = 0;
while(iter.hasNext()){
j++;
int tmp = iter.next();
if(tmp == position){
// 在这个节点后面加上新增节点
list.add(j,node);
// 因为不重复,所以加完直接退出
break;
}
}
}
}
// 这里必须用包装类接收,如果用int下面删除会直接根据索引删除
Integer removeInt = in.nextInt();
list.remove(removeInt);
for(int i:list){
System.out.print(i + " ");
}
}
}
}