One, single linked list basic operation
(1) Clear single-linked list
while(L->next){ p=L->next; L->next=p->next; free(p); }
Analysis: P points to the next field of L, and the next field of L is in the next field (P=l->next) that points to p, which is actually the next field where L points to L. Then empty P
Keep looping, know l->next = = NULL
(2) destruction of single-linked list
while(L){ p=L->next; free(L); L=p;}
(3) Single-linked list to determine whether it is empty
if(L->next==NULL) returnTRUE;else returnFALSE;
(4) Table length for single linked list
int ListLength(LinkList L){ p=L->next; i=0; while(p){ i++; p=p->next; } return i;}
(5) How to find elements in a single linked list
p=L->next; i=1while&& p->data!=e){ p=p->next; i++; } if(p){ return i; } else{ return0; }
Analysis: Start the search from the first node, search succeeds, return the bit order; otherwise, return 0
Second, reverse order to establish a single linked list
Analysis:
- Create an empty single-linked list of lead nodes
- Enter the data element AI, create a new node p, and insert p after the head node to become the first node.
- Repeat the 2nd step until you complete the creation of the single-linked list.
The code is as follows:
voidCreatelist_n (linklist&L, int n) {//Reverse input n data elements, set up a single linked list of leading nodesL=(linklist) malloc (sizeof (Lnode)); L -Next= NULL; for (i= 1; I<=N I++) {P=(linklist) malloc (sizeof (Lnode)); scanf&P -Data);//INPUT element valueP -Next=L -Next L -Next=P//Insert}
Third, sequential establishment of single-linked list
Analysis:
- Create an empty single-linked list of lead nodes
- Enter the data element AI, create a new node, and insert it into the last node after the tail node p.
- Repeat the 2nd step until you complete the creation of the single-linked list
The code is as follows:
L = (LinkList) malloc (sizeof (LNode));LNULL; p=L;for(i=1;i<=n;i++){ q=(LinkList)malloc(sizeof(LNode)); scanf(&q->data); q->next=p->next; p->next=q; p=q;}
Linear table-linked list (iii)