Insertion in Singly Linked List
Insertion in Singly Linked List
1. Insert at Beginning
Struct node
{
Int data;
Struct node *next;
};
Struct node *head, *newnode;
Newnode = (struct node *) malloc(size of (struct
node));
Printf(“Enter data you want to insert:”);
Scanf(“%d”, &newnode->data);
Newnode->next = head;
Head = newnode;
2. Insert at the End
Struct node
{
Int data;
Struct node * next;
};
Struct node *head, *newnode, *temp;
Newnode = (struct node * malloc(sizeof(struct
node));
Printf(“Enter data you want to insert:”);
Scanf(“%d”, &newnode->data);
Newnode->next = 0;
Temp = head;
While (temp->next != 0)
{
Temp = temp->next;
}
Temp->next = newnode;
3. Insert after a given location
Int pos; i=1;
Struct node
{
Int data;
Struct node * next;
};
Struct node * head, *newnode, *temp;
Newnode = (struct node *) malloc(sizeof(struct
node));
Printf(“Enter the position:”);
Scanf(“%d”, &pos);
If (pos > count)
{
Printf (“Invalid position”);
}
Else
{
Temp=head;
While (i < pos)
{
Temp = temp->next;
i++;
}
Printf(“Enter data”);
Scanf(“%d”, &newnode->data);
Newnode->next = temp->next;
Temp->next = newnode;
Struct node
{
Int data;
Struct node *next;
};
Struct node *head, *temp;
DeletefromBeg()
{
// Struct node * temp;
Temp = head;
Head = head->next;
Free(temp);
}