hello everyone,
im having issues with this. i don't know what else to try. i am supposed to add a remove function to delete the last node in the list, i am trying this, but i get an endless loop, and when i change it around it just sits there.

any help would be appreciated! thanks
Val.

public Link deleteLast()
    {
        Link temp = head;
        
        while(temp.next != null)
        temp = temp.next;
            return temp;
    }

Recommended Answers

All 3 Replies

To remove last element from temp LinkedList use temp.pollLast(). It will retrieves and removes the last element of list and returns null if list is empty.

From your code, I'm guessing you have a node call head which hold the begining of the list. The loop in your code :

//this mean loop until your node doesn't has
//any node to point to
while (temp.next != null) 
//advance temp node to be the next node
     temp = temp.next;

so at the end of the while loop, the temp node is now the last node in the list and what you want is to remove the last node. You can modify the code so that it will loop until the node before the last node, the make that node to point to null to terminate the last node from the list.

public Link deleteLast()
    {
        Link temp = head;
        
        while(temp.next!= null)
            if (temp.next.next == null)
                 temp.next = null;
            else temp.next = next;
            return temp;
    }

Just curious, you name your node class name as Link ?

hey thanks!!! that's what was wrong =)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.