import sun.net.www.HeaderParser;
import java.security.PrivateKey;
import java.util.Scanner;
/**
* @author xienl
* @description 链表
* @date 2022/5/30
*/
public class Solution {
public static void main(String[] args) {
MyNode node = new MyNode();
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
scanner.nextLine();
for (int i= 0; i < num; i++){
String str = scanner.nextLine();
String[] split = str.split("\\s+");
if ("insert".equals(split[0])){
node.insert(Integer.parseInt(split[1]), Integer.parseInt(split[2]));
} else if ("delete".equals(split[0])){
node.delete(Integer.parseInt(split[1]));
}
}
node.print();
}
}
/**
* 链表类
*/
class MyNode{
private Node root; // 真实的链表
public MyNode(){};
public void insert(int x, int y){
if (root == null){
root = new Node(y);
return;
}
Node head = new Node(-1, root);
Node pre = head;
while (pre.next != null && pre.next.value != x){
pre = pre.next;
}
pre.next = new Node(y, pre.next);
root = head.next;
}
public void delete(int x){
Node head = new Node(-1, root); // 头节点
Node pre = head;
while (pre.next != null && pre.next.value != x){
pre = pre.next;
}
if (head == null){
return;
}
pre.next = pre.next == null ? null : pre.next.next;
root = head.next;
}
public void print(){
if (root == null){
System.out.println("NULL");
} else {
root.print();
}
}
/**
* 链表
*/
class Node{
private int value;
private Node next;
public Node(){};
public Node(int value){
this.value = value;
}
public Node(int value, Node next){
this.value = value;
this.next = next;
}
public void print(){
System.out.print(this.value + " ");
if (this.next != null){
this.next.print();
}
}
}
}
代码如上,可以直接编译哈。
讨论算法的话,可以私聊我哈,一起学习
博客提及代码可直接编译,还邀请大家私聊讨论算法,共同学习,涉及Java链表数据结构相关内容。
5万+

被折叠的 条评论
为什么被折叠?



