for removing the last element from a chain in my linked list?

Action *temp = head; //Action is my node

	while(temp != 0)
	{
		if(temp->link == tail) //tail is my last node
		{
			delete last;

			tail = temp;
			tail->link = 0;

			return;
		}

		temp = temp->link;
	}

I guess my real question is, will this leave any leaks behind, or cause me problems in the future use of my list? Thanks

Recommended Answers

All 5 Replies

The variable "last" you use in line 7 isn't defined, nor is it given a value anywhere.

If your list has only a single element, then presumably after you remove it, you need to set head to 0. Nowhere in the code is it possible for that to happen.

I think he means to delete tail.
@OP: during a list implementation you will have a lot of transversal and deletion code, for that you might want to make a helper function to make your functions clearer. Also your code doesn't work if there is only 1 element, where the head and the tail point to the same element.

Your function to delete the last element from the linked list is good enough. However, do take note of the issue raised by arkoenig regarding the code

delete last;

which apparently doesn't appear to be meaningful in the codes given.

Do take note about the existence of other data structures like Stack and Queue which may be a better solution in place of linked list. If you are always looking to delete the last element, you may want to consider using stack. Anyway, it all depends on the problem that you're solving. Happy coding!

Im sorry, that is supposed to be delete tail. I was implementing this function in a separate project to test it out and i had named it differently.

Thanks for the replys.

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.