gpt4 book ai didi

java - 打印单个喜欢的列表以进行测试

转载 作者:行者123 更新时间:2023-12-01 13:23:42 25 4
gpt4 key购买 nike

我有一个应用程序,它应该是显示等待注册类(class)的学生的示例(使用单个链接列表)。但是,我不确定如何测试它。更具体地说,如何打印所有节点的数据值来测试我的添加/删除方法。到目前为止我的代码如下,如果我没有提供足够的信息,请告诉我。预先感谢您的帮助!

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;
}
}

最佳答案

重写自定义类 StudentRegistration 中的 toString() 方法。

例如:

@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();

}

然后在你的 main 中你只需调用

System.out.println(studentRegistrationObject);

关于java - 打印单个喜欢的列表以进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21897196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com