Bobert
Bobert

Reputation: 15

Deleting the last node of a singly linkedlist

Below is the function to delete the last node of a singly linked list. I don't understand, why are we creating a temp Node? I tried doing it without the temp Node and used the node itself but the output doesn't delete the last node. Also, since we are using the temp Node, why are we returning the node and not temp? We aren't making any changes to node, so how is node affected?

public Node deleteLastNode(Node node)
{
    if (node.next == null || node == null)
        return null;
    Node temp = node;

    while (temp.next.next != null)
    {
        temp = temp.next;
    }
    temp.next = null;
    return node;
}

Upvotes: 1

Views: 101

Answers (4)

Rob
Rob

Reputation: 1057

First of all you need to switch this to conditions like this

if (node.next == null || node == null) to 
if (node == null || node.next == null) 

this may cause null pointer exception. next..I think that temp is need to hold data before assigning null so that the real reference would not loose data.

Upvotes: 1

diginoise
diginoise

Reputation: 7630

To navigate linked list to its last node, you need a pointer (cursor) pointing at a node you are supposing to be last pending the test this.next == null.

Without the temporary node (a.k.a cursor, or pointer) how could you interact with any node in the list?

Upvotes: 0

Sergey Prokofiev
Sergey Prokofiev

Reputation: 1885

I don't understand why we are creating a temp Node?

That's because you're storing current iteration node in that temp variable.

I tried doing it without the temp Node and used the node itself but the output doesn't delete the last node.

Code needed to provide any feedback.

Also, since we are using the temp Node, why are we returning node and not temp?

Because you're returning reference to the head of the list, it just doesn't have last element anymore.

We aren't making any changes to node which so how is node getting affected?

You're deleting last node here temp.next = null;

Hope it makes things a little bit clear for you.

Upvotes: 1

Mohammed Siddiq
Mohammed Siddiq

Reputation: 558

The reason why temp node is usually used is that the node is the head/starting of the list, which is the only representation of the list we have (by definition of a linked list). Hence we do not want to alter the head(or representation of our list) and that is the reason node is returned from the method - which means we are returning the updated list after deletion is performed.

Upvotes: 1

Related Questions