I thought of sharing the code snippet. It just does the basic operations like inserting a node at the end of the linked list and deletion of any particular node in the linked list. The deletion of a node in linked list is based on the data of the node and not on the index at which data is located.
You can improve on the code by making the
Code: C
//Basic Linked list operation
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
/*
*
* Program for single linked list which inserts / deletes
* data into linked list.
*
*/
// Structure templates
struct list
{
int no;
struct list *shortlink;
};
typedef struct list node;
node *head = NULL;
void init(node*);
void InsertNode();
void DeleteNode();
void DisplayList();
void main()
{
char ch = 'n';
int opt;
do
{
printf("\nEnter your option\n");
printf("\n1. Insert a node\n");
printf("\n2. Delete a particular node\n");
printf("\n3. Display all the nodes\n");
printf("\n4. Exit the application\n");
scanf("%d",&opt);
switch(opt)
{
case 1:
InsertNode();
DisplayList();
break;
case 2:
DeleteNode();
DisplayList();
break;
case 3:
DisplayList();
break;
case 4:
ch = 'y';
break;
}
}while(ch != 'y');
printf("\nDone by \"SHABBIR\"\n");
getch();
}
void init(node *current)
{
printf("\nEnter number\n");
scanf("%d",¤t->no);
current->shortlink = NULL;
}
void InsertNode()
{
node *newnode;
newnode=(node*)malloc(sizeof(node));
init(newnode);
if(head == NULL)
{
head = newnode;
}
else
{
node *current = head;
// Move to the end of the linked list
while(current->shortlink!=NULL)
{
current=current->shortlink;
}
if(current->shortlink==NULL)
{
newnode->shortlink = current->shortlink;
current->shortlink = newnode;
}
}
}
void DeleteNode()
{
node* current = head;
int rno;
node *newnode,*temp;
printf("\nEnter the number whose node you want to delete\n");
scanf("%d",&rno);
newnode=current;
if(current->no==rno)
{
// Deleting the first node
newnode=current;
current=current->shortlink;
free(newnode);
head = current;
return;
}
else
{
while(newnode->shortlink->shortlink!=NULL)
{
// Checking condition for deletion of
// all nodes except first and last node
if(newnode->shortlink->no==rno)
{
temp=newnode->shortlink;
newnode->shortlink=newnode->shortlink->shortlink;
free(temp);
head = current;
return;
}
newnode=newnode->shortlink;
}
if(newnode->shortlink->shortlink==NULL && newnode->shortlink->no==rno)
{
// Checking condition for deletion of last node
free(newnode->shortlink);
newnode->shortlink=NULL;
head = current;
return;
}
}
}
void DisplayList()
{
node* current = head;
while(current!=NULL)
{
printf("\n %d ",current->no);
current=current->shortlink;
}
}
DeleteNode function independent on data stored and making it based on which index needs deletion.
eng.sarah
like this

