题解 | #【模板】链表#

【模板】链表

https://www.nowcoder.com/practice/97dc1ac2311046618fd19960041e3c6f

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    static class Node {
        private final int val;
        private Node next;

        public Node(int val) {
            this.val = val;
            //JVM在进行类加载是next会自动初始化为null
            // this.next=null;
        }
    }

    static class MyList {
        private final Node dummyHead;

        public MyList() {
            dummyHead = new Node(-1);
        }

        public void insert(int x, int y) {
            Node cur = dummyHead;
            while (true) {
                if (cur.next == null || cur.next.val == x) {
                    Node newNode = new Node(y);
                    newNode.next = cur.next;
                    cur.next = newNode;
                    break;
                }
                cur = cur.next;
            }
        }

        public void delete (int x) {
            Node cur = dummyHead;
            while (cur != null) {
                if (cur.next != null && cur.next.val == x) {
                    Node GCnode = cur.next;
                    cur.next = cur.next.next;
                    /*
                     * 虽然我们逻辑上删除了链表中的结点,但是对象之间的强引用会阻止垃圾收集器回收它们,
                     * 在删除节点后,我们手动设置被删除节点的  next 引用为 null,以便Java的垃圾收集器可以回收该节点。
                     */
                    GCnode = null;
                    break;
                }
                cur = cur.next;
            }
        }

        public Node getHead() {
            return dummyHead.next;
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(
            new InputStreamReader(System.in)
        );
        StringBuilder sb = new StringBuilder();
        int commandsCount = Integer.parseInt(br.readLine());
        MyList list = new MyList();
        while (commandsCount > 0) {
            String[] command = br.readLine().split(" ");
            if (command[0].equals("insert")) {
                int x = Integer.parseInt(command[1]);
                int y = Integer.parseInt(command[2]);
                list.insert(x, y);
            } else if (command[0].equals("delete")) {
                int x = Integer.parseInt(command[1]);
                list.delete(x);
            }
            commandsCount--;
        }
        Node cur = list.getHead();
        if (cur == null) {
            sb.append("NULL");
        } else {
            while (cur != null) {
                sb.append(cur.val).append(" ");
                cur = cur.next;
            }
        }
        System.out.println(sb);
    }
}

全部评论

相关推荐

在校生实习:我觉得平时学校肯定有各种大作业吧。包装一下写项目里。特长那块喧宾夺主了,项目肯定是大头。特长里比如:熟悉vscode,这个感觉不具有吸引性。简要介绍你会什么语言,什么工具等就行了。同26找实习,我是个超级菜鸡😭大家一起加油
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务