When doing some algorithm problems about the singly linked list , it is often necessary to invert the singly linked list , which is more convenient to operate, but generally speaking, it is more convenient to reverse the singly linked list. But this is not only a bit of a waste of storage space, but also easy to get confused, so if the space complexity is required to be O(1) , then it is even more impossible to use the head insertion method to achieve inversion.
At this time, a specific algorithm can be used to realize the inversion of the singly linked list. Its idea is probably as follows:
Scan the singly linked list from the beginning to the end, and make the next node point to the previous node in turn by specific means. In this way, if a cycle goes on, the singly linked list realizes the reverse order operation.
即从
A---->A---->A----->A------>A----->A----->
变为
<-----A<-----A<-----A<-----A<-----A<-----A
It may seem a little hard to understand, I wrote the scratch paper and code myself, I hope it can help you understand:
Because of the recent postgraduate entrance examination, the time is tight, and the writing may be a bit irregular, hehe, hope for understanding
C language implementation:
//将一个单链表 L 就地逆序存放
LinkList ReverseList(LinkList &L){
if(L->next == NULL) //若单链表为空则直接返回
return L;
LNode *q = L, *p = L->next, *temp; //定义q指针指向前一个元素,p指针指向后一个元素,temp为临时指针
q->next = NULL; //将即将形成的链表链尾的指针域置 NULL
while(p != NULL){
q->data = p->data; //将后一个元素的值赋值给前一个元素
temp = p->next; //temp暂时记录下一元素
p->next = q; //p指针此时反向指向q,即q将作为p的后继指针
q = p; //q指针后挪
p = temp; //p指针后挪
}
q->data = 0; //将最后形成的头结点数据域清 0
L = q; //最终 将 q赋值给 L 作为头结点
return L;
}
Run the screenshot: