Just trying to get my head around linked lists and I'm trying to all the standard container functions..

For a singly-linked list are these algorithms correct?

void pop_front(const T& t)
	{
		// Deallocate memory pointed to by head
		node<T>* tempNode = head;
		delete head;

		// Get new head
		head = tempNode->next;
	}

	void pop_back(const T& t)
	{
		// Deallocate memory pointed to by tail
		delete tail;

		// Get new tail
		node<T>* currentNode = head;
		for (size_t i=0; i<sizet-2; i++)
		{
			currentNode = currentNode->next;
		}
		tail = currentNode;
		tail->next = NULL;
	}

Cheers!

pop_front is wrong. First you make a copy of head then delete it. When you delete head that also invalidates the copy tempNode. What you want to do is set head then delete tempNode

What are you going to use that parameter for ?

void pop_front(const T& t)
{
    if( head != NULL)
    {
        node<T>* tempNode = head;

        // Get new head
        head = tempNode->next;
        // OR just this
        head = head->next;

        // Deallocate memory pointed to by head
        delete tempNode;
    }
}

Yeah that makes sense, cheers!

(The parameters were just a careless copy+paste job from push_front() and push_back().)

I'm still not sure about pop_back though.. "size-2" doesn't seem very elegant. I was trying to look through the std::vector header file for some inspiration but it's hard to make sense of it..

you could just use a while statement

void pop_back(const T& t)
{
    // Deallocate memory pointed to by tail
    delete tail;
    tail = NULL;
    // Get new tail
    node<T>* currentNode = head;
    while(currentNode->next != NULL)
    {
             tail = currentNode;
             currentNode = currentNove->next;	
    }
    if( currentNode == head)
    {
          head = tail = NULL;
    }
}
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.