赞
踩
-
-
- 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();
- }
- }
-
- }
- }
代码如上,可以直接编译哈。
讨论算法的话,可以私聊我哈,一起学习
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。