我有一个应用程序,它应该是显示等待注册课程的学生的示例(使用单个链接列表)。但是,我不确定如何测试它。更具体地说,如何打印所有节点的数据值以测试我的添加/删除方法。到目前为止,我的代码如下,如果我没有提供足够的信息,请告诉我。在此先感谢您的帮助!
public class StudentRegistration<E>
{
private static class Node<E>
{
/** The data value. */
private E data;
/** The link */
private Node<E> next = null;
/**
* Construct a node with the given data value and link
* @param data - The data value
* @param next - The link
*/
public Node(E data, Node<E> next)
{
this.data = data;
this.next = next;
}
/**
* Construct a node with the given data value
* @param data - The data value
*/
public Node(E data)
{
this(data, null);
}
public E getData()
{
return data;
}
}
/** A reference to the head of the list */
private Node<E> head = null;
/** The size of the list */
private int size = 0;
/** Helper methods */
/** Remove the first occurance of element item.
@param item the item to be removed
@return true if item is found and removed; otherwise, return false.
*/
public boolean remove(E item)
{
if(item != null)
{
remove(item);
return true;
}
else
return false;
}
/** Insert an item as the first item of the list.
* @param item The item to be inserted
*/
public void addFirst(E item)
{
head = new Node<E>(item, head);
size++;
}
/**
* Remove the first node from the list
* @returns The removed node's data or null if the list is empty
*/
private E removeFirst()
{
Node<E> temp = head;
if (head != null)
{
head = head.next;
}
if (temp != null)
{
size--;
return temp.data;
} else
{
return null;
}
}
/** Add a node to the end of the list
*@param value The data for the new node
*/
public void addLast(E value)
{
// location for new value
Node<E> temp = new Node<E>(value,null);
if (head != null)
{
// pointer to possible tail
Node<E> finger = head;
while (finger.next != null)
{
finger = finger.next;
}
temp = finger.next;
} else head = temp;
}
}
答案 0 :(得分:1)
覆盖自定义类toString()
中的StudentRegistration
方法。
例如:
@Override
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("[");
Node<T> aux = this.head;
boolean isFirst = true;
while(aux != null){
if(!isFirst){
sb.append(",");
}
isFirst = false;
sb.append(aux.data.toString());
aux=aux.next;
}
return sb.append("]").toString();
}
然后在你的主要你只需要打电话
System.out.println(studentRegistrationObject);