Below is a simple program for insertion in a linked list, however, whenever I run the program, it reads only two input values for the list and stops further execution. Why is that? I am unable to catch the issue.
/**** Defining structure of node *****/
class Node{
public:
int data;
Node* next;
Node(int val){
data = val;
next = NULL;
}
};
/**** Inserting node at the end ****/
Node* insertAtEnd(Node* &head, int val){
Node* n = new Node(val);
if(head == NULL){
head = n;
}
Node* tmp = head;
while(tmp->next != NULL){
tmp = tmp->next;
}
tmp->next = n;
return tmp;
}
/**** Menu ****/
int menu(){
int ch;
cout<<"1. Insert node"<<endl;
cout<<"Enter your choice: ";
cin>>ch;
cout<<endl;
return(ch);
}
/**** Driver Code ****/
int main(){
Node* head = NULL; int n, data;
switch(menu()){
case 1:
cout<<"\nEnter number of nodes you want to enter: ";
cin>>n;
for(int i = 0; i<n; i++){
cout<<"Enter data: ";
cin>>data;
insertAtEnd(head, data);
}
break;
default:
cout<<"Wrong Choice";
}
}