无法在C中显示双向链表

时间:2013-06-04 07:27:50

标签: c

大家好我已经制作了双链表的程序并且没有错误但是当我插入并显示列表然后列表为空时,以下是我的代码for dispay和addatbeg function``

void addatbeg()// Ins`erting element in the beg
{
    struct dsnode*r,*q=p;
    if(p==NULL) //If the list is empty
    {
        //creating a new node
        p=(struct dsnode*)malloc(sizeof(struct dsnode));
        p->prev=NULL;
        p->data=item;
        p->next=NULL;
    }
    else
    {
        while(q->next!=NULL)//Traverse the linked list till the last node is reached 
        {
            q=q->next;
        }

        //add a new node in the end
        r=(struct dsnode*)malloc(sizeof(struct dsnode));
        r->prev=q;
        r->data=item;
        r->next=NULL;
        q->next=r;
    }
}

void dis() //Display
{
    while(p!=0)
    {
        printf("%2d ",p->data);
        p=p->next;
    }
}

2 个答案:

答案 0 :(得分:2)

您的代码不完整,但如果p是全局代码,则dis()会通过修改p来显示并清空列表。

答案 1 :(得分:1)

添加到Ben所说的内容:您将使用p的副本解决清空列表问题,如下所示:

struct dsnode *q = p;
while (q != 0)
{
    printf("%2d ", q->data);
    q = q->next;
}
相关问题