Singularly Linked List Write the C function to insert a node
Solution
// inserting items in the front or beginning of linkedlist
#include<iostream>
#include<conio.h>
#include<malloc.h>
using namespace std;
struct node
{
int info;
struct node *next;
}*start, *temp;
void insert_beg(int);
void display();
void main()
{
start = NULL;
int item, choice, location, element, position;
again:
cout << \"\ Select the option \ 1.Insert values at Beginning of the linked list \ 2.Display Linked list \ 3.Exit Program\ \";
cout << \"Enter Choice : \";
cin >> choice;
switch (choice)
{
case 1:cout << \"Enter item to insert : \";
cin >> item;
insert_beg(item);
goto again;
case 2:cout << \"\ Inserted item = \";
display();
goto again;
case 3: exit(0);
default:break;
}
getch();
}
void insert_beg(int item)
{
temp = (node*)malloc(sizeof(node));
temp->info = item;
temp->next = start;
start = temp;
}
void display()
{
temp = start;
while (temp != NULL)
{
cout << temp->info << \" \";
temp = temp->next;
}
cout << \"\ \";
}
// Program for deletion
#include<iostream>
#include<conio.h>
#include<malloc.h>
using namespace std;
struct node
{
int info;
struct node *next;
}*start, *temp;
void insert_beg(int);
void display();
void deleteNode(struct node *, int);
void delete_beg();
void main()
{
start = NULL;
int item, choice, location, element, position;
again:
cout << \"\ Select the option \ 1.Insert values at Beginning of the linked list \ 2.Display Linked list \ 3.Delete Node \ 4.Exit Program\ \";
cout << \"Enter Choice : \";
cin >> choice;
switch (choice)
{
case 1:cout << \"Enter item to insert : \";
cin >> item;
insert_beg(item);
goto again;
case 2:cout << \"\ Inserted item = \";
display();
goto again;
case 3:cout << \"Enter item to delete : \";
cin >> item;
deleteNode(start, item);
goto again;
case 4: exit(0);
default:break;
}
getch();
}
void insert_beg(int item)
{
temp = (node*)malloc(sizeof(node));
temp->info = item;
temp->next = start;
start = temp;
}
void display()
{
temp = start;
while (temp != NULL)
{
cout << temp->info << \" \";
temp = temp->next;
}
cout << \"\ \";
}
void deleteNode(struct node *head, int deleteItem)
{
struct node *ptr, *preptr;
ptr = start;
preptr = start;
if (ptr->info == deleteItem)
{
delete_beg();
}
else
{
while (ptr->info != deleteItem)
{
preptr = ptr;
ptr = ptr->next;
}
preptr->next = ptr->next;
free(ptr);
}
}
void delete_beg()
{
struct node *ptr;
ptr = start;
start = start->next;
free(ptr);
}




