题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
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(); int headValue = in.nextInt(); // 尾指针 MyNode tail = new MyNode(-1, null); // 头指针 MyNode header = new MyNode(headValue, tail); // 构建链表 for (int i = 0; i < n - 1; i++) { int value = in.nextInt(); int node = in.nextInt(); // 查找对应节点 MyNode myNode = findMyNode(header, node); // 如果找不到 if (myNode == null) { MyNode next = header.getNext(); // 先将节点插入头结点后面 header.addNext(new MyNode(value, next)); } else { // 如果找到节点,直接插入到对应节点后面 MyNode next = myNode.getNext(); myNode.addNext(new MyNode(value, next)); } } // 删除值 int deleteValue = in.nextInt(); MyNode it = header; StringBuilder stringBuilder = new StringBuilder(); while (it.hasNext()) { int value = it.getValue(); if (value != deleteValue) { stringBuilder.append(value).append(" "); } it = it.getNext(); } System.out.println(stringBuilder.toString().trim()); } } public static class MyNode { private int value; private MyNode next; public MyNode(int value, MyNode next) { this.value = value; this.next = next; } public int getValue() { return this.value; } public MyNode getNext() { return this.next; } public boolean hasNext() { return this.next != null; } public void addNext(MyNode next) { this.next = next; } } public static MyNode findMyNode(MyNode iter, int value) { if (iter == null) { return null; } while (iter.hasNext()) { MyNode next = iter.getNext(); if (next.getValue() == value) { return next; } iter = next; } return null; } }
头结点没有变化,变化的是后面的节点。由于链表需要判断结束比较麻烦,所以构造了一个尾节点,用于判断是否到达链表尾端。找到对应节点的话,将对应节点的下一个指针先保存起来,然后放入到新节点的后续节点中,接着再用新节点替换掉对应节点的后续节点。如果找不到对应节点,一般是第一个,直接加到头结点后面。
#每日一题挑战#