【发布时间】:2014-10-10 09:37:37
【问题描述】:
我已经成功地从头开始创建了一个 LinkedList。到目前为止它只能添加数据。没有删除或任何类似的花哨的东西。
我可以添加字符串、整数等,但打印添加的数据时遇到问题。我怎么做?我想我得先循环一遍,但是怎么做呢?'
这是我的节点类:
public class Node {
T data;
Node<T> nextNode;
public Node(T data) {
this.data = data;
}
public String toString () {
return data +"";
}
}
这里是 LinkedList 类:
public class LinkedList <T> {
Node<T> head;
Node<T> tail;
public void add (T data) {
// where to add statements. if its empty or not
Node<T> node = new Node<T> (data);
if (tail == null) { // empty list
// nothng in the node = tail = node;
head = node;
tail = node;
}
else { // non empty list, add the new boogie train to the tail
tail.nextNode = node; // new node pointing to tail
tail = node; // update
}
}
这是主要的。我从 Linkedlist 创建一个对象并使用通用的 add 方法添加我的数据。但是如何在屏幕上打印出来呢?提前致谢。
public static void main(String[] args) {
LinkedList<Object> list = new LinkedList<Object> ();
list.add(15); // boogie1 = head
list.add(16);
list.add(10); // boogie end = tail
【问题讨论】:
-
抱歉代码混乱。当我尝试添加代码时,它似乎总是搞砸了。
-
您只需复制它并按 Ctrl+K。如果您将其格式化并使用空格进行缩进,那么它将保持这种状态。
标签: java