Reputation: 337
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.
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;
}
}
Upvotes: 2
Views: 752
Reputation: 11301
You haven't set the new value for Tail
in the negative case:
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.
Upvotes: 4