简体   繁体   English

链接列表擦除节点

[英]Linked list erasing node

CAR *removing(int *numberofstructures,CAR *first)
{
    char categorytoerase[51];
    CAR *helpnode,*actual;
    int i;
    int number_1=0;
    helpnode=(CAR*)malloc(sizeof(CAR));
    actual=(CAR*)malloc(sizeof(CAR));
    actual=first;
    number_1=*numberofstructures;
    helpnode=NULL;
    scanf("%s",categorytoerase);
    for(i=1;i<=number_1;i++)
    {
        if (actual->znacka==categorytoerase)
        {
            if (helpnode != NULL) {
                helpnode->next=actual->next;
                free((void *)actual);
                actual=helpnode->next;
            }
            else
            {
                first = actual -> next;
                free((void *)actual);
                actual = first;
            }
        }
        else{
            helpnode=actual;
            actual=actual->next;
        }
    }
    return first;
}

I want to make function that will remove nodes from linked list first you have to enter the string. 我要创建一个将要从链接列表中删除节点的函数,首先必须输入字符串。 It should erase that nodes which have car category name like entered string. 它应该删除具有汽车类别名称的节点,例如输入的字符串。

This looks A LOT like homework.... So in the spirit of being that dick that doesn't write the answer for you I will tell you the idea of deleting a node. 这看起来很像家庭作业。...因此,本着不会给您编写答案的家伙的精神,我将告诉您删除节点的想法。

Nodes contain their data and an address that points to the next node. 节点包含其数据和指向下一个节点的地址。

So since you know that, you can create a method that... 因此,既然您知道这一点,就可以创建一种方法...

Starts at the head and has a reference to the current node and the previous node 从头开始,并引用当前节点和上一个节点

as you search the list for the node that needs to be deleted you are constantly cycling the current and previous node variables. 在列表中搜索需要删除的节点时,您将不断循环当前节点和先前节点的变量。

When you find the node you are looking for you set the previous nodes next address pointer to the next address pointer of the node you are trying to delete. 找到要查找的节点后,将前一个节点的下一个地址指针设置为要删除的节点的下一个地址指针。

Good luck chief! 祝你好运!

AMR is right. AMR是正确的。 It will be easier to delete nodes if you have a doubly-linked list, so include both a previous and next pointer in the struct for your nodes. 如果您有一个双向链接列表,则删除节点会更容易,因此在节点的结构中同时包含上一个指针和下一个指针。 Basically, here's how the delete will happen in pseudocode (after you've found have a pointer to the node you want to delete): 基本上,这是在伪代码中进行删除的方式(在找到要删除的节点的指针之后):

IF todelete.prev != NULL THEN
   todelete.prev.next = todelete.next
ELSE
   list.head = todelete.next
END IF
IF todelete.next != NULL THEN
   todelete.next.prev = todelete.prev
ELSE
   list.tail = todelete.prev
END IF

FREE todelete

The if conditions are important; 如果条件很重要; otherwise the program will crash and the logic doesn't really work -- you can't very well replace something that doesn't exist. 否则,程序将崩溃并且逻辑无法真正起作用-您不能很好地替换不存在的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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