题解 | #【模板】链表#

【模板】链表

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


public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = Integer.parseInt(sc.nextLine());
        MyLinked linked = new MyLinked();
        for (int i = 0; i < n; i++) {
            String[] tempData = sc.nextLine().split(" ");
            switch (tempData[0]) {
                case "insert":
                    linked.insert(Integer.parseInt(tempData[1]), Integer.parseInt(tempData[2]));
                    break;
                case "delete":
                    linked.delete(Integer.parseInt(tempData[1]));
                    break;
            }
        }
        linked.output();
        sc.close();
    }
}

class MyLinked {
    private Node head;//头节点

    private int length;//链表的长度

    //创建一个单链表
    public MyLinked() {
        this.length = 0;
        head = new Node(null);
    }

    //向链表中添加数据
    public void insert(int value, int data) {
        Node p = this.head;//前指针
        Node q = this.head.getNext();//后指针
        while (q != null && q.getData() != value) {//加上q!=null,防止找到最后节点不结束而出现空指针错误(放前面)
            p = q;
            q = q.getNext();
        }
        if (q == null) {//链表中没有所查找的数据,新数据插入末尾
            p.setNext(new Node(data, null));
        } else {//找到目标数据
            p.setNext(new Node(data, q));
        }
        this.length++;
    }

    //删除链表中的数据
    public void delete(int data) {
        if (isEmpty()) {
            return;
        }
        Node p = this.head;
        Node q = this.head.getNext();
        while (q != null && q.getData() != data) {
            p = q;
            q = q.getNext();
        }
        if (q != null) {
            //找到,删除
            p.setNext(q.getNext());
            this.length--;
        }
    }

    //判空
    public boolean isEmpty() {
        return this.length == 0;
    }

    //链表中的数据输出
    public void output() {
        if (isEmpty()) {
            System.out.println("NULL");
            return;
        }
        Node temp = this.head.getNext();
        for (int i = 0; i < this.length; i++) {
            if (i == this.length - 1) {
                System.out.print(temp.getData());
                break;
            } else {
                System.out.print(temp.getData() + " ");
                temp = temp.getNext();
            }
        }
    }
}

class Node {
    private int data;//数据域

    private Node next;//指针域

    //创建一个头节点
    public Node(Node next) {
        this.next = next;
    }

    //创建一个实际节点
    public Node(int data, Node next) {
        this.data = data;
        this.next = next;
    }

    public int getData() {
        return this.data;
    }

    public Node getNext() {
        return this.next;
    }

    public void setNext(Node next) {
        this.next = next;
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务