题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
import java.util.Scanner; // 注意类名必须为 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(); //节点个数 ListNode head = new ListNode(in.nextInt()); //后续输入总是两个节点为一组,共n-1组,1表示头结点 for(int i = 0; i < n-1; i++){ ListNode secondNode = new ListNode(in.nextInt()); int firstKey = in.nextInt(); //遍历链表找firstNode的位置 ListNode node = head; while(node != null && node.key != firstKey){ node = node.next; } secondNode.next = node.next; node.next = secondNode; } //结束,获取要删除的节点 int removeKey = in.nextInt(); //设置虚拟头结点 ListNode dummyHead = new ListNode(-1, head); ListNode node = dummyHead; while(node.next != null && node.next.key != removeKey){ node = node.next; } node.next = node.next.next; //删除node.next节点 //输出链表数据 ListNode iterator = dummyHead.next; while(iterator != null){ System.out.print(iterator.key + " "); iterator = iterator.next; } } } } //时间复杂度: O(n^2) //节点类 - 单向链表 class ListNode{ int key; ListNode next; ListNode(int key){ this.key = key; this.next = null; } ListNode(int key, ListNode next){ this.key = key; this.next = next; } }