首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >定制LinkedList与官方LinkedList

定制LinkedList与官方LinkedList
EN

Stack Overflow用户
提问于 2018-02-05 22:55:33
回答 1查看 423关注 0票数 2

为了学习和,我是伪重新实现官方LinkedList数据结构,我不太清楚为什么正式的LinkedList看起来像数组,而我的官方LinkedList在调试时看起来像链式节点。

这可能只是调试格式,还是我完全不理解LinkedList的实际实现方式?

CustomNode:

代码语言:javascript
复制
package Ch02_LinkedList;

public class CustomNode {
    private int data;

    CustomNode next = null;

    CustomNode(int data) {
        this.data = data;
    }
}

CustomLinkedList:

代码语言:javascript
复制
package Ch02_LinkedList;

import java.util.LinkedList;

/**
 * Custom implementation of a singly linked list.
 *
 * A double linked list would also contain a "prev" node.
 */
public class CustomLinkedList {
    private CustomNode head;

    public void add(int value) {
        if (this.head == null) {
            this.head = new CustomNode(value);

            return;
        }

        CustomNode current = this.head;

        while (current.next != null) {
            current = current.next;
        }

        current.next = new CustomNode(value);
    }

    public void prepend(int value) {
        CustomNode newHead = new CustomNode(value);
        newHead.next = this.head;
        this.head = newHead;
    }

    public void remove(int index) throws IllegalArgumentException {
        if (this.head == null) {
            return;
        }

        if (index == 0) {
            this.head = head.next;

            return;
        }

        CustomNode current = head;
        int currentIndex = 0;

        while (current.next != null) {
            if (index == currentIndex+1) {
                current.next = current.next.next;

                return;
            }

            current = current.next;
            currentIndex++;
        }

        throw new IllegalArgumentException("No such a index has been found.");
    }

    public static void main(String[] args) {
        CustomLinkedList myList = new CustomLinkedList();
        myList.add(10);
        myList.add(20);
        myList.add(30);
        myList.add(40);
        myList.add(50);
        myList.add(60);
        myList.remove(4);

        LinkedList<Integer> officialList = new LinkedList<>();
        officialList.add(10);
        officialList.add(20);
        officialList.add(30);
        officialList.add(40);
        officialList.add(50);
        officialList.add(60);
        officialList.remove(4);

        System.out.println("Done.");
    }
}

输出:

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-05 23:08:29

IntelliJ在首选项对话框中有一个选项:

为集合类启用可选视图 选择此选项以更方便的格式显示集合和地图。

“数组”视图更便于查看LinkedList的内容,您不认为吗?

如果你不喜欢方便的格式,就关掉它。

如果您的CustomLinkedList实现了Collection,您甚至可以在调试器中获得相同的方便格式,尽管这只是我的猜测,因为我不使用IntelliJ。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48632830

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档