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

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

How can the print() member function be used in a singly linked list implementation in C++?
Here's how you would typically use a `print()` member function to display the contents of a singly linked list in C++:
  1. Define your Node and LinkedList classes:
    class Node {
    public:
        int data; // Or any other data type you want to store
        Node* next; 
    
        Node(int data) {
            this->data = data;
            next = nullptr;
        }
    };
    
    class LinkedList {
    public:
        Node* head;
    
        LinkedList() {
            head = nullptr;
        }
    
        // Other member functions (insert, delete, etc.) ...
    
        void print() {
            Node* current = head;
            while (current != nullptr) {
                std::cout << current->data << " -> ";
                current = current->next;
            }
            std::cout << "NULL" << std::endl;
        }
    };
    
  2. Explanation of the `print()` function:
    • Initialization: `Node* current = head;` creates a pointer named `current` and initializes it to the `head` of the linked list.
    • Traversal: The `while` loop iterates through the list as long as `current` is not `nullptr`.
    • Print Data: `std::cout << current->data << " -> ";` prints the data stored in the current node followed by an arrow.
    • Advance Pointer: `current = current->next;` moves `current` to the next node in the list.
    • NULL Handling: After the loop, "NULL" is printed to indicate the end of the list.
  3. How to use the `print()` function:
    int main() {
        LinkedList myList;
        // Add some nodes to the linked list (implementation of insert function omitted for brevity)
        myList.insert(10);
        myList.insert(20);
        myList.insert(30);
    
        myList.print(); // Output: 10 -> 20 -> 30 -> NULL
    
        return 0;
    }
    
Key Points:
  • Member Function: The `print()` function is a member of the `LinkedList` class, meaning it has access to the list's `head` pointer and can therefore traverse the list.
  • Simple Display: The provided implementation offers a basic way to print the data in each node. You can customize the formatting if needed.

void slist::print() const   //object unchanged
{
slistelem*  temp = h;

while (temp != 0) {     //detect end slist
cout << temp -> data << " -> ";
temp = temp -> next;
}
cout << "\n###" << endl;
}
The value 0 in the while loop represents the end-of-list value. It is guaranteed to be such because the constructor slist::slist() initialized it, and the slist::prepend() function maintains it as the end-of-list pointer value. Notice that the internals of this loop could be changed to process the entire list in some other manner.

SEMrush Software