gpt4 book ai didi

java - 链表转字符串输出

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

我正在构建一些测试只是为了让自己熟悉链接列表。

我正在尝试打印链接列表对象,但没有得到任何结果。很可能我正在做一些我不知道的基本错误。

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、AddFirstOne、AddFirstTwo。

运行后我只得到一个空的控制台输出。我再次对 LinkedLists 感到陌生,我已经做了我能正确想到的所有事情来获得输出。如有任何帮助,我们将不胜感激。

最佳答案

您只需调用返回String的方法,而不是打印列表。改变

test.toString(); // Doesn't print, just returns a String

System.out.println(test); // toString() of test is automatically called

关于java - 链表转字符串输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22739807/

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