我正在构建一些测试,只是为了让我自己熟悉链表。
我试图打印出linkedlist对象,但我没有得到任何结果。很可能是我在做一些我不知道的相当基本的错误。
Node.java
public class Node<E> {
E data;
Node<E> next;
//Constructor One
/** Creates a new node with a null next field.
* @param dataItem The data stored.
*/
Node(E dataItem){
data = dataItem;
next = null;
}
//Constructor Two
/** Creates a new node that references another node.
* @param dataItem //the data stored
* @nodeRef nodRef //The node referenced by new node.
*/
Node(E dataItem, Node<E> nodeRef){
data = dataItem;
next = nodeRef;
}
}
SlinkedList.java
/** Class to represent a linked list with a link from each node to the next node
*
* @author Study
*
* @param <E>
*/
public class SlinkedList<E> {
// Reference to head Node
private Node<E> head = null;
//The number of Items in list
private int size;
/** Add an Item to the front of a list.
* @param item the item to be added*/
public void addFirst(E item){
head = new Node<E>(item, head);
size++;
}
/** Add a node after a given node
*
* @param node //The node preceding the new item.
* @param item //The item to insert.
*/
public void addAfter(Node<E> node, E item){
node.next = new Node<E>(item, node.next);
size++;
}
/** Remove the node after a given node
* @param node, the node before the one to be removed
* @returns the data from the removed node or null if there is no node to remove.
*/
//This will work for all nodes except the first one.
public E removeAfter(Node<E> node){
Node<E> temp = node.next;
if(temp != null){
//Nodes next(node before node to remove) equals temps next(the node after node to remove)
node.next = temp.next;
size--;
return temp.data;
}else{
return null;
}
}
@Override
public String toString(){
Node<E> nodeRef = head;
StringBuilder result = new StringBuilder();
while(nodeRef != null){
result.append(nodeRef.data);
if(nodeRef.next != null){
result.append("==>");
}
nodeRef = nodeRef.next; // Advance down the list.
}
return result.toString();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
SlinkedList<String> test = new SlinkedList<String>();
Node<String> tom = new Node<String>("Tom");
test.addFirst("AddFirstOne");
test.addFirst("AddFirstTwo");
test.toString();
}
}
我期待从toString()方法中打印出Tom, addfirststone, AddFirstTwo。
在运行时,我只得到一个空的控制台输出。再说一次,我是LinkedLists的新手,我已经做了所有我能想到的正确的输出。
不是打印列表,而是调用返回String
的方法。把
test.toString(); // Doesn't print, just returns a String
System.out.println(test); // toString() of test is automatically called