I created a linked list but it’s only printing the first value "1" and not the rest. I have an insert function to insert new nodes and then a show function to print out the node values but it’s only printing the first value.
struct Node {
int n;
Node *next;
};
class LinkedList {
private:
Node *head;
Node *tail;
public:
LinkedList() {
head = NULL;
tail = NULL;
}
~LinkedList(){};
void insert_node(int value) {
Node *new_node = new Node();
new_node->n = value;
new_node->next = NULL;
if (head == NULL) {
head = new_node;
tail = new_node;
}
else {
tail = new_node;
tail->next = new_node;
}
}
void show() {
Node *new_node;
new_node = head;
while (new_node != NULL) {
cout << new_node->n << endl;
new_node = new_node->next;
}
}
};
int main() {
LinkedList L;
L.insert_node(1);
L.insert_node(2);
L.insert_node(4);
L.insert_node(8);
L.show();
}
>Solution :
The lines
tail = new_node;
tail->next = new_node;
means
new_node->next = new_node;
tail = new_node;
Therefore, no link from head to new_node is created.
The lines should be:
tail->next = new_node;
tail = new_node;
to first create link to the new node, and then update the tail pointer.