How to insert data anywhere in the linked list in C language? Then write it into the file ?, Insert
Linked List insertion: (the figure is drawn by an individual) It is difficult to understand because the linked list pointer refers to it, so it is more convenient to assist in drawing.
Struct defined:
Struct student {char ID [11]; // student ID char name [20]; // student name struct student * next; // next pointer pointing to struct student type variable} stu;
Check the code I wrote. The Code has a detailed explanation:
/*************** Function: Insert a student to return: pointer to the table header of the linked list/**************/void insert_message (struct student * head) {FILE * fp; // define the file pointer struct student * pointer, * q, * temp; // p pointer pointing to the new node q pointing to the place where the inserted node fp = fopen ("student.txt ", "wb +"); pointer = head-> next; // skip the header node pointing to the next node InputBox (stu. ID, 11, "Enter the student ID to insert"); while (pointer! = NULL) {if (strcmp (pointer-> ID, stu. ID) = 0) // If You Want To insert a value after 1, enter 1 {fwrite (pointer, sizeof (struct student), 1, fp ); // first write 1 node to the file q = (struct student *) malloc (sizeof (struct student); // open up the new node memory InputBox (stu. ID, 11, "Enter student ID"); strcpy (q-> ID, stu. ID); InputBox (stu. name, 20, "Enter the Student name"); strcpy (q-> name, stu. name); temp = pointer-> next; // assign data 2 after 1 to the temporary temp struct variable pointer-> next = q; // assign the q node to the position pointer = pointer-> n of the original 2. Ext; // assign the q node data (pointer-> next equals to q) to p so that p nodes can write files fwrite (pointer, sizeof (struct student), 1, fp ); // write the input q node Data pointer-> next = temp; // assign the original data at location 2 to the next node of p (because the previous code p = p-> next) p is assigned p-> next pointer = pointer-> next; // p always points to the new node while (pointer! = NULL) {fwrite (pointer, sizeof (struct student), 1, fp); // write the traversal of other nodes into the file pointer = pointer-> next ;} fclose (fp); outtext ("Students inserted successfully! ");} Fwrite (pointer, sizeof (struct student), 1, fp); // traverse the node to write the file pointer = pointer-> next ;}}