Analysis:
Initializes three pointer p1,p2,p3. P1 points to the current node, P2 points to the next node of the current node, and P3 points to the previous node of the current node. The initial value of P1,P2,P3 is: P1 points to the first node, P2 points to the second node, P3 points to the previous node of P1, then the initial value of P1 is null.
P1->next = p3 after reverse order.
Then let the p1,p2,p3 pointer move backwards, repeating the above operation P1->next = p3 until P2 is empty. Then the P1 is the last node of the single-linked list, and the single-linked list's head node points to P1, which completes the reverse operation of the single-linked list.
#include <stdio.h>#include<stdlib.h>typedefintElemtype;//defining the storage structure of a linked listtypedefstructNode {elemtype data; structNode *Next;} Node;typedefstructNode *Linklist;typedefstructNode *Pnode;//Create a single-linked list (single-linked list of lead nodes)Linklist Createlinklist (intNintiscycle);//single-linked list reverse orderintReverselinklist (linklist *L);//traversing a single linked listvoidtraversallist (linklist L);//Create a single linked listLinklist Createlinklist (intNintiscycle) {linklist L= (Pnode) malloc (sizeof(Node));//Head knot PointPnode p, r =L; Elemtype e; for(inti =0; I < n; i++) {printf ("Please enter the number of%d digits", i +1); scanf ("%d", &e); P= (Pnode) malloc (sizeof(Node)); if(p = =NULL) {printf ("Out of space"); Exit (1); } P->data =e; if(i = = n1&& Iscycle = =1) {p->next =L; } Else{p->next =NULL; } if(L = =NULL) {L=p; } Else{R->next =p; } R=p; } returnL;}//single-linked list reverse orderintReverselinklist (linklist *L) {pnode P1, p2, p3; P1= (*l)->next;//P1 point to the first node if(P1 = = NULL) {//The linked list is empty return 0; } P2= p1->next;//P2 points to the second nodeP3 = NULL;//P3 points to the previous node of the P1, so the initial value of P3 is nullP1->next = p3;//in reverse order, the next node of P1 should be P3 while(p2) {P3=P1; P1=P2; P2= p2->Next; P1->next =P3; } (*L)->next =P1; return 1;}//traversing a single linked listvoidtraversallist (linklist L) {Pnode P= l->Next; while(p) {printf ("%d", p->data); P= p->Next; }}intMainintargcConst Char*argv[]) {linklist L= Createlinklist (5,0); Traversallist (L); Reverselinklist (&m); Traversallist (L); return 0;}
Reversing a single linked list