头插法
void ListReverse(SLNode *head)
{
SLNode *p,*q;
p=head->next;
head->next=NULL; //break the contact between "head" and "p(head->next)"
while (p)
{
q=p; //when this step be compiled "p" and "q" point at the same node
p=p->next; //This step must be in this line
q->next=head->next; //when this step be compiled ,it will break the connection between the "q" node and the "q->next" node,
//if we did not do the "p=p->next",node "p" will not get in touch with the "p->next" node
head->next=q;
}
}
首先定义 两个指针,使p指向第一个data(不为NULL),将head和p之间的连接断开 (head->next=NULL;),注意各步骤的顺序,和节点之间的关系。其余解释在代码注释中。
本文介绍了一种使用头插法实现链表反转的方法。通过定义两个指针,其中一个指针遍历原链表,另一个指针用于临时保存当前节点,从而逐步构建新的反转链表。文章详细解释了每一步操作的目的及注意事项。
2899

被折叠的 条评论
为什么被折叠?



