简单链表 C# AddAfter 方法
我在 C# 中使用简单的链接列表,我不知道如何在列表末尾添加元素,有人能帮我吗?
namespace ConsoleApplication1
{
class Class1
{
public class Node()
{
public int Data;
public Node Next;
}
private Node FirstNode=null;
public void AddBefore(int number)
{
Node NewNode=new Node();
NewNode.Next=FirstNode;
NewNode.Data=number;
FirstNode=NewNode;
}
public void AddAfter(int number)
{
if (FirstNode==null)
{
AddBefore(number);
}
else
{
???????????????
}
}
}
}
Im working with simple linked lists in C# and I have no idea how to add elements at the end of the list, colud anyone helpme?
namespace ConsoleApplication1
{
class Class1
{
public class Node()
{
public int Data;
public Node Next;
}
private Node FirstNode=null;
public void AddBefore(int number)
{
Node NewNode=new Node();
NewNode.Next=FirstNode;
NewNode.Data=number;
FirstNode=NewNode;
}
public void AddAfter(int number)
{
if (FirstNode==null)
{
AddBefore(number);
}
else
{
???????????????
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要迭代列表,直到找到最后一个节点,然后将其添加到末尾。像这样的东西:
You need to iterate through your list until you find the last node, and then add it to the end. Something like:
你仍然必须实现 GetLastNode 否则你不会练习任何东西 =P
You'll still have to implement GetLastNode or else you wont practise anything =P
这个问题有点令人困惑。您是否询问如何将节点放置在列表末尾,或者作为列表中的下一项。
那天我不得不为家庭作业做这个(虽然是java)。如果您希望始终将节点添加到列表的末尾,那么您还需要编辑列表类以包含列表的头部和尾部。这将允许您将项目添加到末尾或开头。
如果您希望始终在末尾添加一个节点,那么您可以尝试编辑代码,以便当您在末尾添加一个节点时,前一个节点的下一个节点值将设置为尾部而不是 null。这将始终允许您将一个项目添加到列表的末尾(这是大多数添加方法所做的事情,除非指定了位置)简而言之
:
将
Node tailNode = null;
添加到Class
并添加一个用于获取和设置Node
类的下一个节点的方法。完成此操作后,然后编辑代码,使其看起来像这样:代码可能有点偏离(我还没有真正测试过),但这就是您将要做的事情的主要内容。
The question is kind of confusing. Are you asking how to place a node at the end of the list, or as the next item in the list.
I had to do this for a homework assignment way back in the day (it was java though). If you want to always add a node to the end of the list then you also need to edit your list class to contain a head and tail of the list. This will allow you to add items to the end or beginning.
If you want to always add a node to the end then you could try editing the code so that when you add a node to the end the previous node's next node value will be set to the tail instead of null. This will always allow for you to add an item to the end of the list (which is what most add methods do unless a position is specified anyways)
In short:
Add
Node tailNode = null;
toClass
and add a method that will get and set the next node for theNode
class. Once this is done, then edit the code so that it looks something like this:The code may be a little off (I haven't really tested it) but that is the main picture of what you are going to have to do.