Insertion of new node at first position in circular link list requires creation of new node and setting it's info field. After creation of new node, we make last node points to newly created node and newly created node to the first node of the list. Let us see the algorithm for insertion :
Algorithm for insertion at first position in circular link list:
In this algorithm, TAIL is pointer to last node and PTR is node to be inserted at first. The step are as follows:- Create new node PTR
- Set the INFO field of PTR
- If list have no node i.e. [TAIL == NULL]
- TAIL = PTR
- PTR->NEXT = PTR [PTR will point to itself]
- Else
- PTR->NEXT = TAIL->NEXT [PTR's next will point to first node]
- TAIL->NEXT = PTR [TAIL's next pointer will point to PTR]
- End If
Function to insert node at first position in circular link list:
void insertAtFirst(NODE **tail, int info){
NODE *ptr = (NODE*) malloc(sizeof(NODE));
ptr->info = info;
if(*tail == NULL){ //no nodes in list
ptr->next = ptr;
*tail = ptr;
}
else{
ptr->next = (*tail)->next;
(*tail)->next = ptr;
}
}
Program to insert at first position in the circular 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 *tail = NULL;
insertAtFirst(&tail, 1);
insertAtFirst(&tail, 2);
traverse(&tail);
return 0;
}
void insertAtFirst(NODE **tail, int info){
NODE *ptr = (NODE*) malloc(sizeof(NODE));
ptr->info = info;
if(*tail == NULL){ // no node in list
ptr->next = ptr;
*tail = ptr;
}
else{
ptr->next = (*tail)->next;
(*tail)->next = ptr;
}
}
void traverse(NODE **tail){
NODE *temp = *tail;
if(*tail){
do{
printf("%d ", temp->next->info);
temp = temp->next;
} while(temp != *tail);
}
}
Output:2 1
Comments
Post a Comment