【数据结构】(单链表)带头链表就地逆置
程序员文章站
2024-03-22 11:46:04
...
带头链表就地逆置(就地的意思为 空间复杂度为1)
方法一
算法思想:链表的逆置采用非递归的方法使用了三个指针详见代码
// 带头链表就地逆置(就地的意思为 空间复杂度为1)
void Reverse2(LNode *&head){
if(head->next->next==NULL||head->next==NULL) //链表中只有一个元素不需要逆置
return;
LNode *pre=NULL; //前驱节点
LNode *current=head->next; //工作结点
LNode *tail=NULL;//后继结点
while(current!=NULL){
tail=current->next;
current->next=pre;
pre=current;
current=tail;
}
head->next=pre;//改变头节点指向
}
方法二
头插法逆置链表
本质和头插法一样
//头插法逆置链表
void Reverse3(LNode *&head){
if(head->next->next==NULL||head->next==NULL) //链表中只有一个元素或者链表为空时不需要逆置
return;
LNode *cur,*tail;
cur=s=head->next;
head->next=NULL;
while(cur){
tail=cur->next;
cur->next=p->next;
head->next=cur;
cur=tail;
}
}