我创建了一个单独的链接列表,它给出了以下错误。不确定有什么问题,蚂蚁建议
错误/ OP - 列表是javaTest.LinkedListcreation@1540e19d
我不确定输出中的这个值是什么意思。
处理完成,退出代码为0
public class LinkedList{
public static void main (String[] a){
LinkedListcreation L1 = new LinkedListcreation();
L1.addNodeAtEnd("1");
System.out.print("List is " + L1);
}
}
class LinkedListcreation {
int listcount;
node head;
LinkedListcreation() {
head = new node(0);
listcount=0;
}
node Temp;
void addNodeAtEnd(Object d){
node Current = head;
Temp = new node(d);
while (Current.getNext()!= null){
Current = Current.getNext();
}
Current.setNext(Temp);
listcount++;
}
}
class node {
Object data;
node next;
node(Object d) {
next = null;
this.data=d;
}
node(Object d, node nextNode) {
next = nextNode;
this.data=d;
}
public Object getdata(){
return data;
}
public void setdata(int d){
data = d;
}
public node getNext(){
return next;
}
public void setNext (node nextValue){
next = nextValue;
}
}
答案 0 :(得分:1)
您的代码没问题,但为了打印有关对象的有用信息(本例中的列表),您需要覆盖toString
类中的LinkedListcreation
方法。
例如:
public String toString() {
return "List with " + this.listcount + " nodes.";
}
答案 1 :(得分:0)
您正在尝试打印列表对象而不是您添加的元素,而不是您看到的不是错误。检查java中的toString()方法,了解你看到的输出。
修改您的main(),如下所示,查看您添加的元素。
public static void main (String[] a){
LinkedListcreation L1 = new LinkedListcreation();
L1.addNodeAtEnd("1");
System.out.print("List is " + L1.head.next.data);
}
输出:列表为1
答案 2 :(得分:0)
正如大家所说,你必须覆盖toString()
。在这里你有正确的实现:
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
sb.append(head.data.toString());
node n;
while(n = head.getNext() != null)
sb.append(", " + n.data.toString());
sb.append("]");
return sb.toString();
}
答案 3 :(得分:0)
您的代码没有任何错误。如果要在列表中打印节点,只需在LinkedListcreation类中添加另一个函数,该函数将迭代列表并打印每个节点的数据。在LinkedListcreation类中添加此块。
public void printList(){
node current = head.next;
while(current!=null){
System.out.println("node's data is: "+ current.getdata());
current = current.getNext();
}
}
同样在您的主函数中,使用列表的对象L1调用上述函数。
L1.printList();
答案 4 :(得分:-1)
代码有编译错误。请尝试更正下面的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class LinkedList
{
static void Main(String[] a){
LinkedListcreation L1 = new LinkedListcreation();
L1.addNodeAtEnd("1");
Console.WriteLine("List is " + L1);
}
}
public class LinkedListcreation
{
int listcount;
node head;
public LinkedListcreation()
{
head = new node(0);
listcount = 0;
}
node Temp;
public void addNodeAtEnd(Object d)
{
node Current = head;
Temp = new node(d);
while (Current.getNext() != null)
{
Current = Current.getNext();
}
Current.setNext(Temp);
listcount++;
}
}
public class node
{
Object data;
node next;
public node(Object d)
{
next = null;
this.data = d;
}
node(Object d, node nextNode)
{
next = nextNode;
this.data = d;
}
public Object getdata()
{
return data;
}
public void setdata(int d)
{
data = d;
}
public node getNext()
{
return next;
}
public void setNext(node nextValue)
{
next = nextValue;
}
}
}