Now we will see how to delete node at first position in singly link list.
Algorithm to delete node at first position in singly link list:
- Set TEMP = START
- If START != NULL
- Make START points to second node i.e. [START = START->NEXT]
- FREE (TEMP)
- End If
Function to delete node at first position in singly link list:
int deleteFirst(NODE **start){
NODE *temp = *start;
int info = -1;
if(*start == NULL){
printf("\nNo nodes exists in the list\n");
}
else{
info = (*start)->info;
*start = (*start)->next;
free(temp);
}
return info;
}
Program to delete node at first position in the singly link list:
#include <stdio.h>
#include <malloc.h>
struct node{
int info;
struct node *next;
};
typedef struct node NODE;
void insertAtFirst(NODE **, int);
int deleteFirst(NODE **);
void traverse(NODE **);
int main(){
NODE *start = NULL;
insertAtFirst(&start, 4);
insertAtFirst(&start, 5);
traverse(&start);
deleteFirst(&start);
printf("\n");
traverse(&start);
return 0;
}
int deleteFirst(NODE **start){
NODE *temp = *start;
int info = -1;
if(*start == NULL){
printf("\nNo nodes exists in the list\n");
}
else{
info = (*start)->info;
*start = (*start)->next;
free(temp);
}
return info;
}
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 4 4
Comments
Post a Comment