What is inversion? For a better understanding, look directly at the picture: (data elements are randomly selected)
Before inversion:
![](https://img-blog.csdnimg.cn/img_convert/abcaac4db7e14033afa22f7adf0fc09d.png)
After inversion:
![](https://img-blog.csdnimg.cn/img_convert/b1062d24770e4b758b9dfc77f78d3a74.png)
The detailed steps are as follows: (Using head insertion method)
①:
The head node does not move, and the pointer p points to the next bit of the head node, that is, p = head->next; the
q pointer points to the next bit of the p pointer, that is, q = p -> next;
since the a element is reversed, in The last bit, so the next value of a should be empty, that is, p->next = NULL;
![](https://img-blog.csdnimg.cn/img_convert/2420eed3150a43f6ac2d3d592ea21424.png)
②:
The pointer p points to the position pointed to by q, that is, p = q; the q pointer moves backward one bit, that is, q = q->next; the
next value pointed to by the head node (that is, the address of the next element) is assigned to the next of p Value, that is, p->next = head->next;
change the value of next of the head node, that is, head->next = p;
![](https://img-blog.csdnimg.cn/img_convert/b43a86c020cd43e8b3719a06ad9361da.png)
![](https://img-blog.csdnimg.cn/img_convert/a462781a53434c31808799d87906afa6.png)
③:
Loop the above steps until the next value of the q pointer is NULL and no longer loop.
![](https://img-blog.csdnimg.cn/img_convert/14320db4c9884cd5aef81ec02e065383.png)
The detailed code is as follows: (the code is not unique, it is for reference only)
void Traverse(Lnode *L)
{
Lnode *p,*q;
if(L->next == NULL)//判断是否为空链表
return ERROR;
p = L->next;
q = q->next;
p->next = NULL;
while(q)
{
p = q;
q =q->next;
p->next = L->next;
L->next = p;
}
}