Now we will see how to delete node at last position in circular link list.
Algorithm to delete node at last position in circular link list:
- Set TEMP1 = START
- If START != NULL
- If START->NEXT == NULL
- START = START->NEXT
- FREE (TEMP1)
- Else
- Traverse the list so that TEMP1 points to last node and TEMP2 points second last node
- TEMP2->NEXT = NULL
- FREE (TEMP1)
- End If;
- If START->NEXT == NULL
- End If;
Function to delete node at last position in circular link list:
int deleteLast(NODE **tail){
NODE *temp;
int info = -1;
if(*tail == NULL){
printf("\nError: List have no node");
}
else{
if(*tail == (*tail)->next){
temp = *tail;
*tail = NULL;
info = temp->info;
free(temp);
}
else{
temp = (*tail)->next; //temp points to first node
while(temp->next != *tail){
temp = temp->next;
}
temp->next = (*tail)->next; //points to first node
info = (*tail)->info; // store the info
free(*tail); // free last node
*tail = temp; // update the *tail to second last node
}
}
return info;
}
Program to delete node 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 insertAtFirst(NODE **, int);
int deleteLast(NODE **);
void traverse(NODE **);
int main(){
NODE *tail = NULL;
insertAtFirst(&tail, 1); // 1
insertAtFirst(&tail, 3); // 3 1
insertAtFirst(&tail, 4); // 4 3 1
traverse(&tail); // 4 3 1
printf("\n");
deleteLast(&tail); // 3 1
deleteLast(&tail); // 3
traverse(&tail);
deleteLast(&tail); //
deleteLast(&tail); // no node
traverse(&tail); //
printf("\n");
return 0;
}
void insertAtFirst(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;
}
}
int deleteLast(NODE **tail){
NODE *temp;
int info = -1;
if(*tail == NULL){
printf("\nError: List have no node");
}
else{
if(*tail == (*tail)->next){
temp = *tail;
*tail = NULL;
info = temp->info;
free(temp);
}
else{
temp = (*tail)->next; //temp points to first node
while(temp->next != *tail){
temp = temp->next;
}
temp->next = (*tail)->next; //points to first node
info = (*tail)->info; // store the info
free(*tail); // free last node
*tail = temp; // update the *tail to second last node
}
}
return info;
}
void traverse(NODE **tail){
NODE *temp;
temp = *tail;
if(*tail){
do{
printf("%d ", temp->next->info);
temp = temp->next;
} while(temp != *tail);
}
}
4 3 1 4 Error in Deletion: List have no node
Comments
Post a Comment