c 双向链表向后打印

标签 c list printing linked-list

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

编辑:我相信问题出在 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/

相关文章:

c++ - OpenCV如何在二进制图像中找到连接组件的列表

javascript - 使用循环定义变量值JS

Java数据结构类似于TreeMap + Hash?

Python代码学院: Making a list with a string

java - 尝试递归打印整数 LinkedList 时出现堆栈溢出错误? ( java )

bash - Flutter 桌面 - 将 PDF 发送到打印机

c - 如何在 pthread 中使用 C popen

c - 通过串行通讯口将流量计读数导入Excel

c - 辨别值 255 是真实数据还是错误输出

python - 动态打印一行