I'm having trouble displaying this linked list I'm trying to build. I have 2 functions so far to append and print. But all it is returning is a single 0.
A linked list is the single, complete structure. However, you are using it for individual nodes. Start by calling your elemental struct a Node and not a LinkedList and you won't confuse everybody.
You shouldn't be sending the memory address of pointers - you end up double-dereferencing in append_ node. The whole point of pointers is that they already contain a memory address.
void append_node(LinkedList** head)
{
int num;
cout << "Enter a number for a new node to enter to the end of list: ";
cin >> num;
LinkedList* Node = new LinkedList(num);
if (*head == nullptr)
{
*head = Node;
return;
}
Node->value = num;Node->next = nullptr;
LinkedList* ptr = *head;
while (ptr->next != nullptr)
{
ptr = ptr->next;
ptr->next = Node;
}
}
This is an assignment and he wanted us to build a certain way. I've took in the changes of setting the -> next = nullptr in struct declaration and also the new node after creation. Now the print function is only displaying the first node.
#include <iostream>
struct LinkedList {
int value {};
LinkedList *next {};
LinkedList() {};
LinkedList(int v) : value {v} {}
};
void append_node(LinkedList** head);
void printlist(LinkedList* head);
int main() {
size_t nodes {};
LinkedList* head {};
do {
std::cout << "How many do you want to input? (At least one entry.): ";
std::cin >> nodes;
} while ((nodes < 1) && (std::cout << "Enter a proper value!\n"));
for (size_t i = 0; i < nodes; ++i)
append_node(&head);
std::cout << "Here is the updated linked list. \n";
printlist(head);
std::cout << '\n';
}
void append_node(LinkedList** head) {
int num {};
std::cout << "Enter a number for a new node to add to the end of list: ";
std::cin >> num;
if (*head == nullptr)
*head = new LinkedList(num);
else {
auto ptr{ *head };
for (; ptr->next != nullptr; ptr = ptr->next);
ptr->next = new LinkedList(num);
}
}
void printlist(LinkedList* ptr) {
for (; ptr != nullptr; ptr = ptr->next)
std::cout << ptr->value << ' ';
}
Note that if nodes are added to the tail of a list, then it is common to also maintain a tail pointer as well as a head pointer. This allows direct tail insertion without L42 for loop. For large populated lists, this for loop on the performance can be significant.