为了学习和,我是伪重新实现官方LinkedList数据结构,我不太清楚为什么正式的LinkedList看起来像数组,而我的官方LinkedList在调试时看起来像链式节点。
这可能只是调试格式,还是我完全不理解LinkedList的实际实现方式?
CustomNode:
package Ch02_LinkedList;
public class CustomNode {
private int data;
CustomNode next = null;
CustomNode(int data) {
this.data = data;
}
}CustomLinkedList:
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.");
}
}输出:

发布于 2018-02-05 23:08:29
IntelliJ在首选项对话框中有一个选项:
为集合类启用可选视图 选择此选项以更方便的格式显示集合和地图。
“数组”视图更便于查看LinkedList的内容,您不认为吗?
如果你不喜欢方便的格式,就关掉它。
如果您的CustomLinkedList实现了Collection,您甚至可以在调试器中获得相同的方便格式,尽管这只是我的猜测,因为我不使用IntelliJ。
https://stackoverflow.com/questions/48632830
复制相似问题