To insert a node at last position of singly list, we need to traverse the list using some temporary pointer so that temporary pointer points to last node of that list. After getting last node into temp, it's next pointer is updated to point to the new node that is to be inserted at last. After that, the next pointer of new node is set to point to nothing for indicating end of the list as it is inserted at last. Here is the algorithm to inserted node at last position of singly link list:
Algorithm to insert node at last position in singly link list:
- Create new node PTR
- Set the INFO field of PTR
- Set PTR->NEXT = NULL
- If the list has no nodes i.e. [START = NULL]
- Make START point to new node PTR i.e. [START = PTR]
- Else
- Traverse the list using TEMP, so that it points to last node
- Make last node's NEXT point to new node PTR i.e. [TEMP->NEXT = PTR]
- End If
Function to insert node at last position in singly link list:
void insertAtLast(NODE **start, int info){
NODE *ptr = (NODE*) malloc(sizeof(NODE));
NODE *temp = *start;
ptr->info = info;
ptr->next = NULL;
if(*start == NULL){
*start = ptr;
}
else
{
while(temp->next != NULL){
temp = temp->next;
}
temp->next = ptr; //last node point to new node ptr
}
}
Program to insert node at last position in the singly link list:
#include <stdio.h>
#include <malloc.h>
struct node{
int info;
struct node *next;
};
typedef struct node NODE;
void insertAtLast(NODE **, int);
void traverse(NODE **);
int main(){
NODE *start = NULL;
insertAtLast(&start, 22);
insertAtLast(&start, 40);
insertAtLast(&start, 55);
traverse(&start);
return 0;
}
void insertAtLast(NODE **start, int info){
NODE *ptr = (NODE*) malloc(sizeof(NODE));
NODE *temp = *start;
ptr->info = info;
ptr->next = NULL;
if(*start == NULL){
*start = ptr;
}
else
{
while(temp->next != NULL){
temp = temp->next;
}
temp->next = ptr; //last node point to new node ptr
}
}
void traverse(NODE **start){
NODE *temp;
temp = *start;
while(temp != NULL){
printf("%d ", temp->info);
temp = temp->next;
}
}
Output: 22 40 55
Comments
Post a Comment