题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
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.hasNextLine()) { // 注意 while 处理多个 case String str = in.nextLine(); Main a = new Main(); a.delete(str); } } public void delete (String str) { String[] s = str.split(" "); int n = Integer.parseInt(s[0]); ListNode head = new ListNode(Integer.parseInt(s[1]), null); int target = Integer.parseInt(s[s.length - 1]); ListNode vhead = new ListNode(); vhead.nextNode = head; for (int i = 2; i < n * 2 - 1; i += 2) { int newValue = Integer.parseInt(s[i]); //2 , 4, 6 int preValue = Integer.parseInt(s[i + 1]);//3, 5, 7 ListNode newNode = new ListNode(newValue, null); ListNode start = vhead.nextNode; while (start != null) { ListNode cur = start; int value1 = cur.value; if (value1 == preValue) { ListNode temp = cur.nextNode; cur.nextNode = newNode; newNode.nextNode = temp; } start = start.nextNode; } } //删除目标节点 ListNode deleteIndex = vhead; while (deleteIndex != null && deleteIndex.nextNode != null) { int value = deleteIndex.nextNode.value; if (value == target) { deleteIndex.nextNode = deleteIndex.nextNode.nextNode; } deleteIndex = deleteIndex.nextNode; } while (vhead != null && vhead.nextNode != null) { System.out.print(vhead.nextNode.value + " "); vhead = vhead.nextNode; } } class ListNode { int value; ListNode nextNode; public ListNode() { } public ListNode(int value, ListNode nextNode) { this.value = value; this.nextNode = nextNode; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public ListNode getNextNode() { return nextNode; } public void setNextNode(ListNode nextNode) { this.nextNode = nextNode; } } }