Simon Sultana
Simon Sultana

Reputation: 243

Delete a node from a linked list

I'm having trouble deleting a node from a linked list by inputting the telephone number of the record ... This is the code that is supposed to do this:

typedef struct record
{   
    char name[20];
    char surname[20];
    char telephone[20];
}Record;

typedef struct node
{
    Record data;
    struct node *next;
}Node;

Node *head = NULL;

void delete() { 
    Node *n = head; 
    Node* previous = NULL;
    Node *next = n;

    int length;
    int valid;
    char telNumber[20];
    char confirm = 1;

   do {
    valid = 0;
    printf("  TELEPHONE NO. (8 digits)   : ");
    gets();
    gets(telNumber);
    length = strlen(telNumber); 
    for (int i = 0; i < length; i++)
    {
        if (!isdigit(telNumber[i]) || (length != 8))
        {
            printf("You enterred an invalid number\n");
            valid = 1; break;
        }
    }

} while (valid == 1);   

while (n != NULL) {
            if (strcmp(&n->data.telephone, telNumber) == 0) {
                if (previous == NULL) {
                    n = n->next;
                    free(head);
                }
                else {
                    previous->next = n->next;
                    free(n);
                    n = previous->next;
                }
            }
            else {
                previous = n;
                n = n->next;
            }
        }
        printf("You have successfully deleted the telephone record");

. . . The record still remains there. Also, when I have two records, if i try to delete the first record, the program doesn't find it

Upvotes: 1

Views: 144

Answers (2)

Sheetal Shetty
Sheetal Shetty

Reputation: 131

Well there is no error in deletion part. Maybe the head is not initialized and passes the null value to 'n'. So, since 'n' has null value, deletion is not possible. Or updated value of n is not returned or passed properly to the main function.

Upvotes: 2

Muhammad Usama
Muhammad Usama

Reputation: 3147

You are not moving the head forward when first node is deleted.

while (n != NULL) {
        if (strcmp(&n->data.telephone, telNumber) == 0) {
            if (previous == NULL) {
                    n = n->next;
                    free(head);
                    head = n; /* missing*/
            }
            ...

Upvotes: 2

Related Questions