In C, how does one delete a node from a linked list ?, C language delete node
The first method:
Delete student records from the list by name */
Void deleteByName(struct STUDENT * head)
{
Struct STUDENT * p, * q;
Char name [20].
If (head = = NULL)
{
Printf (" the linked list is empty. \ n ");
The return;
}
Printf (" please enter the name of the student to be deleted: ");
The scanf (" % s ", name);
For (p = head - > next, q = head; P! = NULL; P = p - > next, q = q - > next)
{
If (STRCMP (p - > name, name) = = 0)
{
Q - > next = p - > next;
}
}
If (p = = NULL)
Printf (" student to delete does not exist." );
The else
Free (p);
}
This method mainly involves q-> next = p-> next, and then releases the memory space occupied by p nodes.
Method 2nd:
/ * * * * * * * * * * * * * * *
Function functions:
Delete the names of students present
Return: pointer to the list header of the linked table
/ * * * * * * * * * * * * * * * /
Struct student* del_message(struct student* head)
{
The FILE * fp.
Pointer struct student * and * temp; //p point new node temp pointer is temporary node
InputBox(stu.ID,11," please enter student ID to delete student name ");
Fp = fopen (" student. TXT ", "wb +");
Pointer = head - > next; // start from the beginning and iterate to the next node
While (pointer! =NULL) // keep traversing if no empty data can be traversed
{
If (STRCMP (pointer->ID)==0) // find the node to delete
{
Temp = pointer; // assigns the nodes found to the temporary temp node variable
Pointer = pointer - > next; // assigns the next node of p node to p node
Free (temp); // frees the memory of the temporary temp node
While (pointer! =NULL) // writes the remaining nodes
{
Fwrite (pointer, sizeof (struct student), 1, fp);
Pointer = pointer - > next;
}
Break;
}
Fwrite (pointer, sizeof (struct student), 1, fp); // start traversing the list and write to the file
Pointer = pointer - > next; //p pointer to new node (next node)
}
The fclose (fp);
Outtextxy (220, 200, "delete attendance student successful!" );
Return the head;
}
This method first finds the p node, that is, the node to be deleted, then assigns it to a temporary temp structure variable, and then assigns the next node of the p node to the p node, finally, the memory occupied by the temp node is released.
Temp = pointer; // assign the node to the temporary temp node variable.
Pointer = pointer-> next; // assign the next node of the p node to the p node.
Free (temp); // release the memory occupied by the temporary temp Node
The second method is to read and write the linked list structure from the file.
Are the two methods the same?