c - 从链表中删除节点

标签 c pointers linked-list nodes

我无法通过输入记录的电话号码从链表中删除节点......这是应该执行此操作的代码:

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/

相关文章:

使用指针算术将数组元素更改为用户输入

c - 返回数组中找到的所有偶数

c - 需要了解C中的一些指针

java - 从 LinkedList 中删除 "links"?

c - valgrind 对 execvp 大小 1 的无效读取

哄骗 GCC 发出 REPE CMPSB

c++ - 在 C++ 中存储未知大小的数据

Java链表序列insertFirst方法插入对象两次

c - 读取 USB 串行端口时的冗余(C;Mac OSX;Arduino)

c - 在我的 TCP 连接中,客户端发送 Hello,但服务器收到 Hellob