I am trying to implement an insert function of the linked but as soon as I add the third element the program just crashes and execution is stopped, even though the same code worked on hackerrank's compiler.
Here is my code.
#include<bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node * next;
Node(int data){
this -> data = data;
this -> next = nullptr;
}
};
Node * insert_tail(Node * head, int data){
Node * node = new Node(data);
if(head == nullptr) return node;
Node * current = head;
while(head -> next != nullptr) current = current -> next;
current -> next = node;
return head;
}
void print_linkedlist(Node * head){
while(head -> next != nullptr){
cout << head -> data << " -> ";
head = head -> next;
}
cout << head -> data << " -> nullptr";
}
int main(){
Node * head = nullptr;
head = insert_tail(head, 1);
head = insert_tail(head, 5);
head = insert_tail(head, 3);
head = insert_tail(head, 5);
head = insert_tail(head, 8);
head = insert_tail(head, 17);
print_linkedlist(head);
return 0;
}
while(head -> next != nullptr)are risky and require additional tests to ensure thatheadis valid before the firsthead -> next. I usually find it better to writewhile(head != nullptr)and build the initial test into the loop.