Today, let ’s talk about inserting nodes
The important thing for me is that the linked list is drawing. Only when the picture can be understood, I will attach a diagram according to my understanding for easy understanding.
Compare with adding nodes first
End increase: first open up space, fill the data
Then connect the linked list, move the pointer to the last node and connect to the new node
void AddListNode(Pt_Stu plist) { Pt_Stu pnode = (Pt_Stu)malloc(sizeof(STU));
printf("input number:"); scanf("%d", &pnode->number); printf("input name:"); scanf("%s", pnode->name); printf("input score:"); scanf("%f", &pnode->math); pnode->pnext = NULL; while (plist->pnext != NULL) { plist = plist->pnext; } plist ->pnext = pnode; }
Header increase: the same space is created and filled with data, but it is added from the head, which is the next node of the short node
Obviously, the code of the head increment method will be simpler and faster. You do n’t need to move the pointer all the way back, but the order is the reverse of the order you entered.
pnode->pnext = plist->pnext;
plist->pnext = pnode;
Inserting a node is similar to adding, only adding a node at a given position in the linked list
It seems that it is also to open up space, fill in data, and connect linked lists
void InsertNode (Pt_Stu plist, int pos) // pos represents the node's position in the linked list { Pt_Stu pnode = (Pt_Stu) malloc ( sizeof (STU)); printf ( " input number: " ); scanf ( " % d " , & pnode-> number); printf ( " input name: " ); scanf ( " % s " , pnode-> name); printf ( " input score: " ); scanf ( " % f ", &pnode->Math); pNode -> pNext = NULL; for ( int I = 0 ; I <POS- . 1 ; I ++ ) { the plist = plist-> pNext; // POS. 1-node is inserted to a position to the front of pnode-> pnext = plist-> pnext; // The next node of the new node points to the node at the original insertion position plist-> next = pnode; // The node at the previous position points to the new node } }
Modifying a node is similar to deleting a node. If you find a node at a specified location, you can reassign the data or use a copy string to solve it.
ps: Speaking of copying strings, I will directly use it in VS2019 because it will report an error without adding '\ 0'. I will choose to write a copy string to solve it.
code show as below
void StrCpy(char* strOld, char const* strNew) { int i; for (i = 0; i < strlen(strNew); i++) { strOld[i] = strNew[i]; } strOld[strlen(strNew)] = '\0'; }
The linked list with empty nodes is here. In fact, we can find that as long as there is a picture in our brain, we can do the addition, deletion, modification and insertion of the linked list. The methods are similar.