题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
import java.util.Scanner;
// 写得很罗嗦
public class Main {
public static class ListNode {
public int val;
public ListNode next;
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public static ListNode insert(int pre, int fro, ListNode head) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode tmpPre = dummy;
ListNode newNode = new ListNode(pre);
while (tmpPre.next != null) {
tmpPre = tmpPre.next;
if (tmpPre.val == fro) {
if (tmpPre.next != null) {
ListNode nextNode = tmpPre.next;
tmpPre.next = newNode;
newNode.next = nextNode;
} else {
tmpPre.next = newNode;
}
}
}
return head;
}
public static ListNode delete(int val, ListNode head) {
if (head == null) {
return null;
} else {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode tmp = dummy;
while (tmp.next != null) {
if (tmp.next.val == val && tmp.next.next != null) {
tmp.next = tmp.next.next;
}
if (tmp.next.val == val && tmp.next.next == null) {
tmp.next = null;
}
tmp = tmp.next;
}
}
return head;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) {
String nextLine = in.nextLine();
if (nextLine == null || nextLine == "") break;
String[] com = nextLine.split(" ");
int len = Integer.parseInt(com[0]);
int valHead = Integer.parseInt(com[1]);
ListNode head = new ListNode(valHead);
for (int i = 2; i < com.length - 1; i += 2) {
int pre = Integer.parseInt(com[i]);
int fro = Integer.parseInt(com[i + 1]);
insert(pre, fro, head);
}
int delVal = Integer.parseInt(com[com.length - 1]);
delete(delVal, head);
while (head != null) {
System.out.print(head.val + " ");
head = head.next;
}
}
}
}
查看15道真题和解析