Node insertion for Bidirectional non-circular linked list (no leading node) using C language
I wrote in my previous blog "(, this gives us a rational understanding of this type of linked list. What we want to achieve today is to insert nodes to a bidirectional non-circular linked list. You can compare and learn how to insert a single-chain table to a single-chain table in C language. Code upload to https://github.com/chenyufeng1991/InsertDoubleLinkedList.
The core code is as follows:
Node * InsertList (Node * pNode, int pos, int x) {int I = 1; int size = sizeList (pNode); Node * pMove; Node * pInsert; pInsert = (Node *) malloc (sizeof (Node); memset (pInsert, 0, sizeof (Node); pInsert-> element = x; pInsert-> next = NULL; pInsert-> prior = NULL; pMove = pNode; // first check whether the pos value is valid if (pos <0 | pos> size) {printf ("% s function execution, the input pos value is invalid. Failed to insert node \ n ",__ FUNCTION _); return pNode;} // The original linked list is an empty linked list and the node is inserted at the first position. If (pNode = NULL & pos = 0) {pNode = pInsert; printf ("% s function execution, x = % d node inserted at position pos = % d \ n ",__ FUNCTION __, pos, x); return pNode ;} // Insert the node to the first node and the last node if (pos = 0) {// Insert the node as the first node pInsert-> next = pNode; pNode-> prior = pInsert; pNode = pInsert;} else if (pos = size) {// The inserted node is the last node while (pMove-> next! = NULL) {pMove = pMove-> next;} pMove-> next = pInsert; pInsert-> prior = pMove;} else {while (pMove! = NULL) {if (I = pos) {// locate the position. Note that the link sequence of the linked list below is very important: pInsert-> next = pMove-> next; pMove-> next-> prior = pInsert; pInsert-> prior = pMove; pMove-> next = pInsert; break;} else {// continue to find the next node I ++; pMove = pMove-> next ;}} printf ("% s FUNCTION execution, insert x = % d at position pos = % d \ n" ,__ FUNCTION __, pos, x); return pNode ;}