【发布时间】:2018-02-05 22:55:33
【问题描述】:
出于学习目的,我正在伪重新实现官方 Java 数据结构,我不太清楚为什么官方 LinkedList 在调试时看起来像一个数组,而我的看起来像链节点。
可能只是调试格式还是我完全错过了 - 理解 LinkedList 的实际实现方式?
自定义节点:
package Ch02_LinkedList;
public class CustomNode {
private int data;
CustomNode next = null;
CustomNode(int data) {
this.data = data;
}
}
自定义链接列表:
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.");
}
}
输出:
【问题讨论】:
-
查看(open-JDK)LinkedList ...它真的不是基于数组的! ...但也许你的 IDE/调试器是罪魁祸首!?? ;) 它是什么 - 智能? ...您是否尝试过实施
java.util.List...?
标签: java debugging data-structures singly-linked-list