Insertion of a new node at first position requires updation of start pointer pointing to first node of the singly link list. It create a new node and make it's next pointer point to first node of the list and then make the start link reference to this new node. The algorithm for the insertion at first position is as below:
Algorithm to insert node at first position in singly link list:
- Create a new node PTR
- Set the INFO field of PTR
- Make PTR point to first node i.e. [PTR->NEXT = START]
- Make START points to PTR i.e. [START = PTR]
Function to insert node at first position in singly link list:
void insertAtFirst(NODE **start, int info){
NODE *ptr = (NODE*) malloc(sizeof(NODE));
ptr->info = info;
ptr->next = *start;
*start = ptr;
}
Program to insert node at first position in singly link list:
#include <stdio.h>
#include <malloc.h>
struct node{
int info;
struct node *next;
};
typedef struct node NODE;
void insertAtFirst(NODE **, int);
void traverse(NODE **);
int main(){
NODE *start = NULL;
insertAtFirst(&start, 4);
insertAtFirst(&start, 0);
insertAtFirst(&start, 5);
traverse(&start);
return 0;
}
void insertAtFirst(NODE **start, int info){
NODE *ptr = (NODE*) malloc(sizeof(NODE));
ptr->info = info;
ptr->next = *start;
*start = ptr;
}
void traverse(NODE **start){
NODE *temp;
temp = *start;
while(temp != NULL){
printf("%d ", temp->info);
temp = temp->next;
}
}
Output: 5 0 4
Comments
Post a Comment