我成功地从头开始创建了一个LinkedList.到目前为止,它只能添加数据.没有删除或任何类似的东西.
我可以添加字符串,整数等但我有打印我添加的数据的问题.我怎么做?我想我必须首先完成它,但是怎么样?
这是我的Node类:
public class Node {
T data;
Node<T> nextNode;
public Node(T data) {
this.data = data;
}
public String toString () {
return data +"";
}
}
Run Code Online (Sandbox Code Playgroud)
这是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
}
}
Run Code Online (Sandbox Code Playgroud)
这是主要的.我从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
Run Code Online (Sandbox Code Playgroud)
将方法toString添加到LinkedList类
public String toString() {
Node<T> curr = head;
StringBuilder sb = new StringBuilder();
sb.append("LinkedList [");
while (curr != null) {
sb.append(curr.data);
if (curr.nextNode != null) {
sb.append(", ");
}
curr = curr.nextNode;
}
sb.append("]");
return sb.toString();
}
Run Code Online (Sandbox Code Playgroud)
然后在main方法中调用它:
System.out.println(list.toString());
Run Code Online (Sandbox Code Playgroud)