The deletion of a single-linked list is to delete the node I of the single-linked list. The steps are as follows:
(1) Find the storage location p of the node ai-1, because the storage address of the node AI in the single-linked list is the pointer field next to its direct forward node ai-1;
(2) Make the p->next point to the direct successor node of AI Ai+1;
(3) Releasing the space of the node AI;
#include <stdio.h>#include <stdlib.h>typedef struct node{intData struct node*next;} NODE;//Tail interpolation to create a single-linked list node*createend(intArr[],intLen) {NODE*head= (NODE*)malloc (sizeof (NODE));//Generating the head node head->Next= NULL; NODE*end= head;//Tail pointer initialization for(inti =0; i < Len; i++) {NODE*p= (NODE*)malloc (sizeof (NODE));//Establish a node for each array element p->data = Arr[i]; End->Next= P;//The node p is inserted into the endpoint after end = p; } end->Next= NULL;//The single-linked list is established, and the pointer field of the endpoint is emptyreturnHead;} Delete node I nodes in a single-linked list*delete(NODE*head,inti) {NODE*p= head;intj =1; while(p->Next&& J < i) {p = p->Next; ++j; }if(p->Next= = NULL | | J > I) {//After the loop, if the final p is empty, or I is0or negative, the position is unreasonable;printf("Position error\n");return 0; } NODE*temp= p->Next; P->Next= temp->Next; Free (p);returnHead;} Note: (1) to set the single-linked list to a length of N, the single-linked list must be guaranteed when it deletes node I1<= i <= n, otherwise illegal;//(2) When i=n+1, although the deleted node does not exist, but its predecessor node exists, it is an endpoint; so the direct forward trend of the truncated point*pexist, it does not mean that a truncated point exists, only if*pExists (that is, p! = NULL) and*pis not an endpoint (that is, p->Next! = NULL) to determine the existence of the truncated point when the J <= I is satisfied. At this point, the time complexity of the algorithm is O (n). Single-linked list print voidPrint(NODE*head){if(head = = NULL)return; NODE*p= head->Next; while(P! = NULL) {printf("%d\ n", P->data); p = p->Next; }}intMain (void) {intArr[] = {1,2,3,4,5,6,7};intlen = sizeof (arr)/sizeof (int); NODE*head= Createend (arr, Len);//Before deletingPrint(head);Delete(Head,5);//After deletionPrint(head);return 0;}
Delete the I-node in a single-linked list