Endrit Shabani
Endrit Shabani

Reputation: 337

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.

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

Answers (1)

Zoran Horvat
Zoran Horvat

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

Related Questions