One, single-linked list insertion
(1) How does a single linked list insert a new element?
In a single-linked list
Ordered pairs:
Become
Legend:
Note: Inserting in a single-linked list only requires modifying the pointer. To insert an element before the first node, modify the pointer to the node (i-1).
(2) What is the code for inserting elements of a single linked list?
The code is as follows:
Status Listinsert (linklist&L, int i, elemtype e) {p=L J=0; while(p&&J<I-1) {P=P -Next++J }if(p&&J==I-1) {s=(linklist) malloc (sizeof (Lnode)); S -Data=E S -Next=P -Next P -Next=SreturnOK; }Else{returnERROR; } }
Analysis: In this algorithm, the single-linked list inserts an element, L is the head pointer of the single-linked list leading to the node, and the new element e is inserted before the first node in the list. The function of the while loop is to look for a node (i-1).
Core algorithms:
Generate new node S
S= (linklist) malloc (sizeof (Lnode));
Assign a value to the new node s
s->data=e;
Let S's next field point to the next field of P, and p will connect with AI
s->next=p->next;
Let p next field point to the next field of S, and P also establishes a contact with S
p->next=s;
Successfully inserted new node E
Legend:
Second, the deletion of single-linked list
(1) How does a single linked list insert a new element?
In a single-linked list
Ordered pairs:
Become
Legend:
Note: When deleting the I node in a single-linked list, go to the node (i-2) in the single-linked list and modify its pointer to a successor.
(2) How to write the code of the deletion element of the single linked list?
The code is as follows:
Status Listdelete (linklist &l,intI, Elemtype &e) {p=l; j=0; while(p->Next&& j<i-1) {p=p->Next; ++j; }if(p->Next&& j==i-1){Q=p->Next; P->Next=Q-Next; E=Q-Next; FreeQ);returnOK; }Else{returnERROR; } }
Analysis: In this algorithm, the single-linked list removes the element, L is the head pointer of the single-linked list leading to the node, and deletes the I node element in a single linked list. The function of the while loop is to look for a node (i-1) and let P point to it .
Core algorithms:
Let Q point to the next field of P to prevent the chain from breaking and, once broken, the elements behind it will not be found.
q=p->next;
Let P point to the next field of Q, in fact P points to the next field of P's next
p->next=q->next;
Let e store the value of the element that Q points to, that is, we want to delete the value, in order to secure, we first want to delete this value to save, to prevent future use
e=q->next;
Empty the memory of the node Q
Free (q);
return OK;
Legend:
Linear table-linked list (ii)