So I am trying to figure out on my own where my linked list program is going wrong. The head is somehow getting updated. I know its a tiny mistake but I just not finding where I am going wrong. is it related to global declaration of the variable ?
#include <iostream>
using namespace std;
struct node {
int data;
struct node* next;
}* head = NULL;
void insert()
{
struct node *newnode, *temp;
temp = (struct node*)malloc(sizeof(struct node));
newnode = (struct node*)malloc(sizeof(struct node));
cout << "Enter the element in the Linked list" << endl;
cin >> newnode->data;
newnode->next = NULL;
if (head == NULL) {
head = newnode;
temp = head;
}
else {
temp->next = newnode;
temp = newnode;
}
}
void display(struct node* p)
{
while (p != NULL) {
cout << " " << p->data << endl;
p = p->next;
}
}
int main()
{
int ch;
do {
cout << "1.To Enter element in the Linked List" << endl;
cout << "2.To DIsplay Element in the Linked List" << endl;
cout << "3.To exit" << endl;
cin >> ch;
switch (ch) {
case 1: {
insert();
break;
}
case 2: {
display(head);
break;
}
}
} while (ch != 3);
return 0;
}