题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
package newCoder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @Author:凌曦
* @Version:1.0
* @Date:2022/7/25-22:45
* @Description: 2 1 2 3 2 5 1 4 5 7 2
* 1 2 表示为
* 2->1
* 链表为2->1
* <p>
* 3 2表示为
* 2->3
* 链表为2->3->1
* <p>
* 5 1表示为
* 1->5
* 链表为2->3->1->5
* <p>
* 4 5表示为
* 5->4
* 链表为2->3->1->5->4
* <p>
* 7 2表示为
* 2->7
* 链表为2->7->3->1->5->4
*/
public class OneWayListDelVal {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] strings = br.readLine().split(" ");
int delVal = Integer.parseInt(strings[strings.length - 1]);
int len = Integer.parseInt(strings[0]);
Node head = new Node(strings[1]);
for (int i = 2; i < strings.length - 1; i += 2) {
int search = Integer.parseInt(strings[i + 1]);
Node insertNode = new Node(strings[i]);
insertNode.insertAfter(head, search);
}
System.out.println(head.delNode(head, delVal).toString());
}
}
class Node {
int value;
Node next;
Node(String value) {
this.value = Integer.parseInt(value);
}
Node delNode(Node head, int delValue) {
Node temp = head;
// 我就是要删头节点,那再见了,我给你我的下一个,江湖再见
if (head.value == delValue) {
return head.next;
}
// 不是,那我给你找
// 下一个不为空?
while (head.next != null) {
// 他的值是你要的
if (head.next.value == delValue) {
// 让他滚,让他的下一个接应
head.next = head.next.next;
break;
}
// 没找到就往下走
head = head.next;
}
return temp;
}
void insertAfter(Node head, int searchValue) {
while (head != null) {
if (head.value == searchValue) {
// 顺序不能换
// 我的下一个是你原来的下一个
this.next = head.next;
// 你的下一个就是我
head.next = this;
break;
}
head = head.next;
}
//找不到就插到最后
// head.next = this;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
Node cur = this;
while (cur != null) {
sb.append(cur.value).append(" ");
cur = cur.next;
}
return sb.toString();
}
}
