Insert linked list nodes in C Language
Adding, deleting, modifying, and querying a linked list are the most basic operations. In my previous blog "delete linked list nodes in C Language", I deleted a node in the linked list. Here we want to insert a node at a certain position.
The core code is as follows:
Node * InsertToPosition (Node * pNode, int pos, int x) {if (pos <0 | pos> sizeList (pNode) {printf ("% s function execution, invalid pos = % d. Failed to insert data \ n ",__ FUNCTION __, pos); return pNode;} Node * pMove; Node * pInsert; pInsert = (Node *) malloc (sizeof (Node); memset (pInsert, 0, sizeof (Node); pInsert-> next = NULL; pInsert-> element = x; pMove = pNode; int I = 1; // here we separately consider pos = 0. if (pos = 0) {pInsert-> next = pNode; pNode = pIns Ert; printf ("% s FUNCTION execution, insert x = % d in pos = % d success \ n" ,__ FUNCTION __, pos, x); return pNode ;} while (pMove! = NULL) {if (I = pos) {pInsert-> next = pMove-> next; pMove-> next = pInsert; printf ("% s function execution, insert x = % d into pos = % d successfully \ n ",__ FUNCTION __, pos, x); break;} I ++; pMove = pMove-> next ;} return pNode ;}