简体   繁体   中英

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

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.

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*/
            }
            ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM