题解 | #从单向链表中删除指定值的节点#

从单向链表中删除指定值的节点

https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            int num = in.nextInt();
            int headVal = in.nextInt();
            Node head = new Node(headVal);
            HashMap<Integer, Node> map = new HashMap<>();
            map.put(headVal, head);

            // 创建链表,并用hashmap来记录当前节点数量和快速寻找对应节点,以便添加新节点
            while (map.size() < num) {
                int val = in.nextInt();
                int prev = in.nextInt();

                Node newNode = new Node(val);
                if (map.get(prev).next != null) {
                    Node temp = map.get(prev).next;
                    map.get(prev).next = newNode;
                    newNode.next = temp;
                } else {
                    map.get(prev).next = newNode;
                }
                map.put(val, newNode);
            }

            // 遍历链表,如果遇到需要移除的节点则不print 
            int removeVal = in.nextInt();
            while (head != null) {
                if (head.val != removeVal)
                    System.out.print(head.val + " ");
                head = head.next;
            }
        }
    }

}

class Node {
    int val;
    Node next;

    public Node(int val) {
        this.val = val;
        this.next = null;
    }
}

全部评论

相关推荐

喜欢疯狂星期四的猫头鹰在研究求职打法:短作业优先
点赞 评论 收藏
分享
04-28 11:34
西北大学 运营
牛客4396号:不好意思,这个照片猛一看像丁真
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务