gpt4 book ai didi

c 双向链表向后打印

转载 作者:行者123 更新时间:2023-11-30 19:19:48 25 4
gpt4 key购买 nike

我试图将我的链表程序变成双向链表,但是,当我尝试向后打印列表时遇到问题。当我尝试向后打印时,它只是运行一个永无止境的循环,而且我不太清楚错误在哪里。如果有人能指出我做错了什么,那将会非常有帮助。

编辑:我相信问题出在 displaybackwards 方法中,但我不知道如何更改它,因为删除它会导致程序崩溃。

这些是我当前代码中我认为可能存在问题的部分:

struct  NODE
{
union
{
int nodeCounter;
void *dataitem;
}item;
struct NODE *link;
struct NODE *backlink;
};

struct NODE *InitList()
{
struct NODE *temp = (struct NODE*)malloc(sizeof NODE);

temp->item.nodeCounter = 0;
temp->link = NULL;
temp->backlink = NULL;
return temp;
}

void Add2List(struct NODE *start, struct NODE *NewNode)
{
struct NODE *current = start;

while (current->link != NULL)
{
current->backlink = current; //problem should be this line
current = current->link;
}
current->link = NewNode;
NewNode->link = NULL;
NewNode->backlink = current;

start->item.nodeCounter++;
}

void DisplayList(struct NODE *start)
{
struct NODE *current = start->link;

while (current != NULL)
{
DisplayNode((struct inventory *)current->item.dataitem);
current = current->link;

}
}

void DisplayBackwards(struct NODE *start)
{
struct NODE *current = start->link;
while(current != NULL && current->link != NULL) //goes until current == last node
{

current = current->link;
current->backlink = current;
}

//when current == last node
while(current != start)// && current->backlink != NULL)
{
DisplayNode((struct inventory*)current->item.dataitem);
current->link = current;
current = current->backlink;
}
}

最佳答案

void DisplayBackwards(struct NODE *start)
{
struct NODE *current = start; //current points to first node
if(current==NULL) //if empty list, return
return;

//now we are sure that atleast one node exists
while(current->link != NULL) //goes until current == last node
{
current = current->link; //keep on going forward till end of list
}

//start from last node and keep going back till you cross the first node
while(current != NULL)
{
DisplayNode((struct inventory*)current->item.dataitem);
current = current->backlink; //go one node back
}
}

关于c 双向链表向后打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23719167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com