| Lesson 7 | A singly linked list |
| Objective | The print() member function |
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;
}
};
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;
}
print() member function, an auxiliary pointer temp will be used to chain down the list. It is initialized to the address of the slist head h. The pointer h cannot be used because its value would be lost, in effect destroying access to the list.
void slist::print() const //object unchanged
{
slistelem* temp = h;
while (temp != 0) { //detect end slist
cout << temp -> data << " -> ";
temp = temp -> next;
}
cout << "\n###" << endl;
}
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.