Following code deletes the node in liked list just by traversing once. Wondering any other alternative method to achieve the same.
Code:Code for deleting a node struct node { int data; struct node *next; }node; struct node *first,*save,*new1; add(int i) { if (!first) { first = (struct node *)malloc(sizeof(node)); first->next = NULL; first->data = i; save = first; } else { new1 = (struct node *)malloc(sizeof(node)); new1->data = i; new1->next = NULL; save->next = new1; save = new1; } } disp2() { struct node *first1 = first; printf("\n\nNumbers are \n"); while ( first1 ) { printf("%d\t",first1->data); first1 = first1->next; } } delete_nth_node_from_end(int n) { struct node *first1,*n_th_node,*save; int count = 0; save = first1 = n_th_node = first; while ( first1->next ) { first1 = first1->next; count++; if ( count == (n-1) ) break; } if ( count < (n-1) ) { printf("Link list is not large enough\n"); return; } if ( first1->next == 0 ) { first = n_th_node->next; free(first); return; } while ( first1->next != 0 ) { first1 = first1->next; save = n_th_node; n_th_node = n_th_node->next; } save->next = n_th_node->next; free(n_th_node); return; } main() { int i; int n; while ( 1 ) { printf("Enter the number:"); scanf("%d",&i); if ( i ) add(i); else break; } printf("\n\nBefore deletion\n"); disp2(); delete_nth_node_from_end(n = 4); printf("\n\nAfter deletion\n"); disp2(); }



LinkBack URL
About LinkBacks


