我正在尝试将链接列表程序设置为双向链接列表,但是,当我尝试向后打印列表时遇到问题。 在我尝试向后打印的那一刻,它只是运行一个永无止境的循环,我无法弄清楚错误的位置。 如果有人能指出我做错了什么,那就非常有帮助。
编辑:我认为问题出在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;
}
}
答案 0 :(得分:1)
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
}
}