Linked List
Singly Linked List
1. Create linked list
Node *createList(Node *list)
{
int n, i;
Node *newNode, *temp;
printf("Enter the how many Node : \n");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
newNode = (Node *)malloc(sizeof(Node));
newNode->next = NULL;
printf("Enter data for %d Node : ", i);
scanf("%d", &newNode->data);
if (list == NULL)
{
list = temp = newNode;
}
else
{
temp->next = newNode;
temp = newNode;
}
}
return list;
}
======================================================
2. Display linked list
void displayList(Node *list)
{
printf("Linked List is : \n");
while (list != NULL)
{
printf("%d\t", list->data);
list = list->next;
}
printf("\n");
}
============================================================
*Insertion in Linked List
1. Insert of Beginning
// Function
Node *insertBeg(Node *list, int value)
{
Node *new_node;
new_node = (Node *)malloc(sizeof(Node));
new_node->data = value;
new_node->next = list;
list = new_node;
return list;
}
=================================================================
2. Insert By Position in linked list
Node *insertValue(Node *list, int pos, int value)
{
Node *temp, *newNode;
newNode = (Node *)malloc(sizeof(Node));
newNode->data = value;
newNode->next = NULL;
if (pos == 1)
{
newNode->next = list;
list = newNode;
}
else
{
temp = list;
for (int i = 1; (i < pos - 1) && (temp != NULL); i++)
{
temp = temp->next;
}
if (temp == NULL)
{
printf("Position is Out of Range !!\n");
return list;
}
else
{
newNode->next = temp->next;
temp->next = newNode;
}
}
return list;
}
===================================================================
*Delete in Linked List
1. Delete by Position
Node *deleteByPos(Node *list, int pos)
{
Node *temp = list, *temp2;
if (pos == 1)
{
list = temp->next;
free(temp);
}
else
{
for (int i = 1; (i < pos - 1) && (temp->next != NULL); i++)
{
temp = temp->next;
}
if (temp == NULL)
{
printf("Position is out of range !! \n");
return list;
}
temp2 = temp->next;
temp->next = temp2->next;
free(temp2);
}
return list;
}
====================================================
2. Delete by Value
Node *deleteByValue(Node *list, int value)
{
Node *temp = list, *temp2;
if (list->data == value)
{
list = temp->next;
free(temp);
}
for (temp = list; temp->next != NULL; temp = temp->next)
{
if (temp->next->data == value)
{
temp2 = temp->next;
temp->next = temp2->next;
free(temp2);
return list;
}
}
printf("The value is not Found !! \n");
return list;
}
===========================================================
* Search Function
Node *search(Node *list, int value)
{
Node *temp = list;
while (temp != NULL)
{
if (temp->data == value)
{
return temp;
}
temp = temp->next;
}
return NULL;
}
=================================================================
0 Comments