输入记录的电话号码,无法从链接列表中删除节点。。。这是应该执行此操作的代码:

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");

.
.
.
记录仍然存在。另外,当我有两条记录时,如果我试图删除第一条记录,程序将找不到它

最佳答案

删除第一个节点时,不会向前移动头部。

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

关于c - 从链表中删除节点,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36745585/

10-11 15:32
查看更多