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

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

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

简单模拟,平平淡淡才是真

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        Node head = new Node(in.nextInt());
        Node dummy = new Node(-1, head);
        while (in.hasNextInt()) {
            Node target = new Node(in.nextInt()); // 插入/删除的结点
            if (in.hasNextInt()) {
                // 插入
                int insert = in.nextInt();
                Node node = dummy;
                while (node != null) {
                    if (node.val == insert) {
                        target.next = node.next;
                        node.next = target;
                        break;
                    }
                    node = node.next;
                }
            } else {
                // 删除
                Node node = dummy;
                while (node.next != null) {
                    if (node.next.val == target.val) {
                        node.next = node.next.next;
                        break;
                    }
                    node = node.next;
                }
            }
        }
        System.out.println(head.toString());
    }
}
class Node {
    public Node() {
    }

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

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

    int val;
    Node next;

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        Node node = this;
        while (node != null) {
            sb.append(node.val).append(" ");
            node = node.next;
        }
        return String.valueOf(sb);
    }
}

全部评论

相关推荐

11-09 12:17
清华大学 C++
out11Man:小丑罢了,不用理会
点赞 评论 收藏
分享
勤奋努力的椰子这就开摆:美团骑手在美团工作没毛病
投递美团等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务