题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.Scanner; public class Main{ public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(System.in); String input = sc.nextLine(); String[] numsStr = input.split(" "); int[] nums = new int[numsStr.length]; for (int i = 0; i < numsStr.length; i++) { nums[i] = Integer.parseInt(numsStr[i]); } int count = nums[0]; int first = nums[1]; int delete = nums[nums.length - 1]; LinkedList<Integer> list = new LinkedList<>(); list.add(first); // 添加节点 for (int i = 2; i < nums.length - 1; i += 2) { int before = nums[i + 1]; int insert = nums[i]; list.add(list.indexOf(before) + 1, insert); } // 删除节点 list.remove(list.indexOf(delete)); for (Integer integer : list) { System.out.print(integer + " "); } } }