题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int nodes = in.nextInt();
LinkedNode head = new LinkedNode(in.nextInt());
for (int i = 1; i < nodes; i++) {
int data = in.nextInt();
int pre = in.nextInt();
LinkedNode current = head;
while (current.data != pre) {
current = current.next;
}
current.next = new LinkedNode(data, current.next);
}
int toRemove = in.nextInt();
if (head.data == toRemove) {
head = head.next;
} else {
LinkedNode current = head;
while (current.next.data != toRemove) {
current = current.next;
}
current.next = current.next.next;
}
StringBuilder sb = new StringBuilder();
LinkedNode current = head;
while (current != null) {
sb.append(current.data).append(" ");
current = current.next;
}
System.out.println(sb.toString().trim());
}
}
class LinkedNode {
int data;
LinkedNode next;
LinkedNode(int data) {
this.data = data;
this.next = null;
}
LinkedNode(int data, LinkedNode next) {
this.data = data;
this.next = next;
}
boolean hasNext() {
return this.next != null;
}
boolean isLast() {
return this.next == null;
}
}
查看20道真题和解析