简体   繁体   中英

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. 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.

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