C++ 双链表,按顺序添加节点
我想让我的双链接列表一直保持排序,并保持头部和尾部节点指针的更新。我设法在所有操作中保持头部指针的更新,但无法跟踪尾部指针。它只将最后一个元素显示为C++ 双链表,按顺序添加节点,c++,sorting,linked-list,C++,Sorting,Linked List,我想让我的双链接列表一直保持排序,并保持头部和尾部节点指针的更新。我设法在所有操作中保持头部指针的更新,但无法跟踪尾部指针。它只将最后一个元素显示为tail->info,但不能返回为doingtail=tail->prev这是我的代码: AddInOrder(node* &head, node* &tail, int number) { node *ptr=head; if (head==NULL || number<head->inf
tail->info
,但不能返回为doingtail=tail->prev代码>这是我的代码:
AddInOrder(node* &head, node* &tail, int number) {
node *ptr=head;
if (head==NULL || number<head->info) {
node*temp=new node;
temp->info=number;
temp->next=head;
temp->prev=NULL;
head=temp;
tail=temp;
return 0;
}
while(ptr->next!=NULL && ptr->next->info<number) {
ptr=ptr->next;
}
node*temp=new node;
temp->info=number;
temp->next=ptr->next;
temp->prev=ptr;
ptr->next=temp;
while(ptr->next!=NULL) {
ptr=ptr->next;
}
tail=ptr;
return 0;
}
addinoder(节点*&头,节点*&尾,整数){
节点*ptr=头部;
如果(head==NULL | | numberinfo){
node*temp=新节点;
温度->信息=数量;
温度->下一步=头部;
temp->prev=NULL;
压头=温度;
尾=温度;
返回0;
}
而(ptr->next!=NULL&&ptr->next->infonext;
}
node*temp=新节点;
温度->信息=数量;
temp->next=ptr->next;
温度->上一个=ptr;
ptr->next=温度;
while(ptr->next!=NULL){
ptr=ptr->next;
}
tail=ptr;
返回0;
}
@JonathanPotter是对的。“在中链接新节点时,您没有设置ptr->prev。”这就是问题所在。
这段代码对我来说很好。请参阅修改,添加了一些设置prev节点的部分。代码可能有点混乱,但您可以理解逻辑并编写更好的代码
int AddInOrder(node* &head, node* &tail, int number)
{
node *ptr=head;
node*temp=new node;
temp->info=number;
if ( head==NULL )
{
temp->next=head;
temp->prev=NULL;
head=temp;
tail = temp;
return 0;
}
if ( number<head->info )
{
temp->next=head;
temp->prev=NULL;
head->prev = temp;
head=temp;
return 0;
}
while(ptr->next!=NULL && ptr->next->info<number)
{
ptr=ptr->next;
continue;
}
if (ptr->next != NULL)
{
ptr->next->prev = temp;
}
temp->next=ptr->next;
temp->prev=ptr;
ptr->next=temp;
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
tail=ptr;
return 0;
}
int addinoder(节点*&头部,节点*&尾部,整数)
{
节点*ptr=头部;
node*temp=新节点;
温度->信息=数量;
if(head==NULL)
{
温度->下一步=头部;
temp->prev=NULL;
压头=温度;
尾=温度;
返回0;
}
如果(数字信息)
{
温度->下一步=头部;
temp->prev=NULL;
压头->上一个=温度;
压头=温度;
返回0;
}
而(ptr->next!=NULL&&ptr->next->infonext;
继续;
}
如果(ptr->next!=NULL)
{
ptr->next->prev=温度;
}
temp->next=ptr->next;
温度->上一个=ptr;
ptr->next=温度;
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
tail=ptr;
返回0;
}
使用调试器时发现了哪些问题?“但无法返回到执行tail=tail->prev;
”-我正在尝试了解一种情况,在这种情况下,您可能会首先希望这样做,好像它会将您的尾部指针放在不应该放在的地方;而不是列表的最后一个节点上。假设我键入6,9,1,2,3,当我从头部指针开始显示它们时,它会显示1,2,3,6,9,但从尾部开始显示到头部它给出9,然后是6,然后它停止在它不应该继续的地方,就像3,2,1我想以相反的方式打印列表,所以我从尾部开始,然后返回当你链接一个新节点时,你没有设置ptr->prev
。当你在列表的头部添加一个新节点时,你正在擦除你的尾部
指针。还是同样的问题。继续下一个债券是直接的,但当我从尾部开始,想要回到上一个债券时,它不能正确地返回。我想我对上一个债券的连接有问题,无论如何谢谢你的关注,我会在这方面做更多的工作。