Delete linked list nodes in C Language
Adding, deleting, modifying, and querying linked list nodes is the most basic operation. This blog will delete nodes. For other operations, refer to the blog "basic operations for implementing linked lists in C language. There are two types of deleting a node:
(1) Delete A node at a certain position of I;
(2) Determine whether the x value is in the linked list. If yes, delete the node;
The core code is as follows:
// Delete Node * deletePosElement (Node * pNode, int pos) at the pos position {// a header Node is required to maintain Node * pHead; Node * pMove; int I = 1; if (pos <= 0 | pos> sizeList (pNode) {printf ("% s function execution, invalid pos value input, failed to delete node \ n ", __function _); return NULL;} pHead = pNode; pMove = pNode; // Delete the first node if (pos = 1) {pMove = pMove-> next; pNode = pMove; free (pHead); printf ("% s function execution, pos = 1 position deleted successfully \ n ", __function _); return pNode;} while (pMove! = NULL) {if (I = pos-1) {break;} I ++; pMove = pMove-> next;} free (pMove-> next ); pMove-> next = pMove-> next; printf ("% s FUNCTION execution, delete pos = % d position element \ n" ,__ FUNCTION __, pos ); return pNode;} // determines whether the x value is in the linked list. If yes, delete the Node * deleteXElement (Node * pNode, int x) {// The first two pointers and the last two pointers of a Node, pMovePre is the previous Node of pMove * pMovePre; Node * pMove; if (pNode = NULL) {printf ("% s function execution, the linked list is empty, failed to delete x = % d \ n ",__ FUNCTION __, x); return NULL;} pMovePr E = pNode; pMove = pMovePre-> next; // consider the first node if (pMovePre-> element = x) {pNode = pMove; free (pMovePre ); return pNode;} while (pMove! = NULL) {if (pMove-> element = x) {// find the previous node pMovePre-> next = pMove-> next; free (pMove) of the node ); break;} // synchronize forward pMove = pMove-> next; pMovePre = pMovePre-> next;} if (pMove = NULL) {printf ("% s function execution, x = % d does not exist. Failed to delete data \ n ",__ FUNCTION __, x); return pNode;} printf (" % s FUNCTION execution, deleted x = % d \ n ",__ FUNCTION __, x); return pNode ;}