【发布时间】:2022-01-13 22:05:11
【问题描述】:
我的情况
- 仅使用类创建对象列表
这就是代码的工作原理
- 使用
ListRatings类,我可以创建Rating列表(不使用c# 库System.Collections.Generic 提供的列表方法)
(你可以在下面的代码中看到哪些属性和方法有类ListRatings和类Rating)
问题
当我尝试打印我添加到列表中的所有评分时,我的程序只打印第一个和最后一个!
我的代码
类 ListRating:
public class ListRatings
{
private Rating first;
private Rating last;
public ListRatings()
{
first = null;
last = null;
}
public void InsertNewRat(Rating rating)
{
if (first == null)
{
first = rating;
last = rating;
}
else
{
first.setNext(rating);
last.setNext(rating);
}
}
public void PrintRats()
{
Rating e = first;
Console.WriteLine(e.getMatter());
Console.WriteLine(e.getDate());
Console.WriteLine(e.getRate());
e = e.getNext();
Console.WriteLine(e.getMatter());
Console.WriteLine(e.getDate());
Console.WriteLine(e.getRate());
e = e.getNext();
Console.WriteLine(e.getMatter());
Console.WriteLine(e.getDate());
Console.WriteLine(e.getRate());
}
}
班级评分:
public class Rating
{
private int rate;
private string matter;
private DateTime date;
private Rating next;
public Rating(int rate, string matter, DateTime date)
{
this.rate = rate;
this.matter = matter;
this.date = date;
next = null;
}
public int getRate()
{
return rate;
}
public string getMatter()
{
return matter;
}
public DateTime getDate()
{
return date;
}
public Rating getNext()
{
return next;
}
public void setNext(Rating valutazione)
{
next = valutazione;
}
}
主要:
static void Main(string[] args)
{
ListRatings lr = new ListRatings();
Rating r1 = new Rating(9, "Math", new DateTime(2021, 10, 5));
Rating r2 = new Rating(10, "sport", new DateTime(2021, 11, 3));
Rating r3 = new Rating(6, "English", new DateTime(2021, 11, 7));
lr.InsertNewRat(r1);
lr.InsertNewRat(r2);
lr.InsertNewRat(r3);
lr.PrintRats();
Console.ReadKey();
}
输出
Math
05/10/2021 00:00:00
9
English
07/11/2021 00:00:00
6
程序停止并说错误:System.NullReferenceException [在第二个e.getNext(); 我在类ListRating 中使用]
通过此输出,您可以看到正在打印第一个并跳转到最后一个而不打印第二个。
我需要的输出是
Math
05/10/2021 00:00:00
9
Sport
10
03/11/07 00:00:00
English
07/11/2021 00:00:00
6
对不起我的英语不好
【问题讨论】:
-
你检查过这个实现的链表吗? geeksforgeeks.org/linked-list-implementation-in-c-sharp
-
与标准列表相比,链表有什么好处?
-
我们的老师让我们去做,我的意思是它一点也不差。当我们可以用简单的方式做某事时,我们经常用困难的方式做某事,但这就像训练一样。也为此:链表是对象的有序集合。那么是什么让它们与普通列表不同呢?链表与列表的不同之处在于它们在内存中存储元素的方式。列表使用连续的内存块来存储对其数据的引用,而链表将引用存储为它们自己元素的一部分。
-
一个优点是,从一个适度大的链表中间插入或删除元素会更快,因为您更新指针而不是复制可能很大的内存块。