I am writing this code for insertion at the tail of a linked list. When I call the function in the main block there is an error in the tail parameter. Can someone tell why? I made a function for insertion at head, but it works absolutely fine.
code -
class Node {
public:
int data;
Node* next;
//constructor type 1
Node(int data) {
this -> data = data;
this -> next = NULL;
}
};
void insertAtTail(Node* &tail, int data) {
//New node create
Node* temp = new Node(data);
tail -> next = temp;
tail = temp;
}
int main() {
insertAtTail(tail, 20);
print(tail);
}```
The error says it all: "undeclared identifier 'tail'"
Your main
function suddenly references tail
without first telling what tail
is. It makes no sense to insert a node if you don't have anything to insert it into.
You would also need a head
variable to have a reference to the first node in the list.
When you call your print
method, you'd better pass the head
of the list. If you pass tail
, then print
will only print the tail node of the list, and it seems likely you want print
to print the whole list.
Finally, you need to take care of the case where your list is empty (nullptr
) and where you call insertAtTail
to insert the very first node of the list. In that case tail
will be nullptr
and it would be wrong to access tail->next
in that situation. Moreover, you would need to also set the head of the list. So I'd suggest that insertAtTail
takes a parameter for the head
too. That way it can set the head
to the new node in case it is the very first node of the list.
Code:
void insertAtTail(Node* &head, Node* &tail, int data) {
Node* temp = new Node(data);
if (head == nullptr) { // If this is the first node of the list
head = temp;
} else { // Only when there is already a tail node
tail -> next = temp;
}
tail = temp;
}
void print(Node* head) {
while (head != nullptr) {
std::cout << head->data << " ";
head = head->next;
}
std::cout << "\n";
}
int main() {
Node* head = nullptr; // A list has a head
Node* tail = head; // ...and a tail.
insertAtTail(head, tail, 10); // Also pass the head
insertAtTail(head, tail, 20);
insertAtTail(head, tail, 30);
print(head); // Print the whole list, not just the tail
}