C++ Linked Lists   «Prev  Next»
Lesson 5A singly linked list
Objective The prepend() member function

C++ prepend() function

Here's what you need to know about adding characters to the beginning of a C++ string: Common Methods to "Prepend" in C++
  1. `insert()`: This is the most flexible way to insert characters at any position within a string, including the beginning:
       #include 
       #include 
    
       int main() {
           std::string str = "world";
           str.insert(0, "Hello, ");  // Inserts at index 0 (the beginning)
           std::cout << str << std::endl;  // Output: Hello, world
       }
       
  2. Operator `+` (Concatenation): You can concatenate strings, with the new string being placed at the front:
       std::string str = "world";
       std::string greeting = "Hello, ";
       std::string new_str = greeting + str;
       std::cout << new_str << std::endl;  // Output: Hello, world
       
  3. push_front() (for `std::deque`) If you're working with a `std::deque` (double-ended queue), you have a dedicated `push_front()` function for efficiently adding elements to the beginning.
Important Considerations
  • Efficiency: If you're prepending frequently within a loop, `insert()` could become less efficient due to repeatedly shifting existing characters in the string. In such cases, consider:
    • Reserving space: Use `string::reserve` to pre-allocate memory if you know the approximate final string size.
    • Using `std::deque`: If order is less important and you need frequent insertion at both the front and back, a `std::deque` might be more suitable.


Examine the prepend() member function of the singly linked list implementation.

The member function prepend() is used to build the list structure:
void slist::prepend(char c)
{
   slistelem*  temp = new slistelem;//make element
    
   temp -> next = h;        //link to slist
   temp -> data = c;
   h = temp;                   //update head of slist
}
A list element is allocated from free store, and its data member is initialized from the single argument c. Its link member next is set to the old list head. The head pointer h is then updated to point at this element as the new first element of the list.

Node Node::prepend(const std::string& tag, const Attributes& attributes, const std::string& text) {
	Node child = prepend(tag);
	for(auto attribute : attributes){
		child.pimpl_->append_attribute(attribute.first.c_str()) = attribute.second.c_str();
	}
	if(text.length()>0) child.pimpl_->append_child(pugi::node_pcdata).set_value(text.c_str());
	return child;
}