我创建了一个单链表,它给出了以下错误。不确定出了什么问题,蚂蚁建议
错误/OP-列表为javaTest.LinkedListcreation@1540e19d
我不确定Output中的这个值是什么意思。
进程已完成,退出代码为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;
}
}
您的代码还可以,但为了打印有关对象(本例中为列表)的有用信息,您需要覆盖LinkedListcreation
类中的toString
方法。
例如:
public String toString() {
return "List with " + this.listcount + " nodes.";
}
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();
}
您正试图打印列表对象,而不是您添加的元素,并且您看到的内容没有错误。查看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
您的代码没有任何错误。如果你想打印列表中的节点,你只需要在LinkedListcreate类中添加另一个函数,它将迭代你的列表并打印每个节点的数据。将此块添加到LinkedList创建类中。
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();
代码存在编译器错误。尝试在下方更正代码
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;
}
}
}