Insertion of new node at last 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 point to first node of the list. After that the pointer pointing to last node is updated to point to new created node.
Algorithm for insertion at last position in circular link list:
The algorithm uses TAIL as pointer to last node of list and PTR is the newly created node that is to be inserted at last position. The steps 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 will point to first node]
- TAIL->NEXT = PTR [last node will point to PTR]
- TAIL = PTR [TAIL will point to PTR which is now last node]
- End If;
Function to insert node at last position in circular link list:
void insertAtLast(NODE **tail, int info){
NODE *ptr = (NODE*) malloc(sizeof(NODE));
ptr->info = info;
if(*tail == NULL){
ptr->next = ptr;
*tail = ptr;
}
else{
ptr->next = (*tail)->next;
(*tail)->next = ptr;
*tail = ptr;
}
}
Program to insert at last position in the circular 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 *tail = NULL;
insertAtLast(&tail, 1);
insertAtLast(&tail, 2);
insertAtLast(&tail, 3);
traverse(&tail);
return 0;
}
void insertAtLast(NODE **tail, int info){
NODE *ptr = (NODE*) malloc(sizeof(NODE));
ptr->info = info;
if(*tail == NULL){
ptr->next = ptr;
*tail = ptr;
}
else{
ptr->next = (*tail)->next;
(*tail)->next = ptr;
*tail = ptr;
}
}
void traverse(NODE **tail){
NODE *temp = *tail;
if(*tail){
do{
printf("%d ", temp->next->info);
temp = temp->next;
} while(temp != *tail);
}
}
1 2 3
Comments
Post a Comment