[英]How do I get the last element ( the tail) in the list?
I am trying to create Single linked list but I don't know what I am doing wrong. 我正在尝试创建单链表,但是我不知道自己在做什么错。
After inserting elements 5,6,7,2,3,4 the tail should be 4 but I am getting 3 and I don't understand why. 插入元素5,6,7,2,3,4尾后应该是4,但我得到3,我不明白为什么。
Here is my code: 这是我的代码:
public void Insert(int x)
{
Node a = new Node(x);
if (Head == null)
{
Head = Tail = a;
}
else
{
Tail = Head;
while (Tail.Next != null)
{
Tail = Tail.Next;
}
Tail.Next = a;
a = Tail;
}
}
You haven't set the new value for Tail
in the negative case: 在负数情况下,您尚未为
Tail
设置新值:
public void Insert(int x)
{
Node a = new Node(x);
if (Head == null)
{
Head = Tail = a;
}
else
{
Tail.Next = a;
Tail = a;
}
}
On a related note, you don't have to search for the tail in the negative case, because you already have the Tail
variable ready. 与此相关的是,您不必在负数情况下搜索尾巴,因为您已经准备好了
Tail
变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.