0

大家好,我已经编写了双向链表程序,没有错误,但是当我插入并显示列表时,列表为空,以下是我的显示代码和 addatbeg 函数

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;
    }
}
4

2 回答 2

2

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

于 2013-06-04T07:31:58.503 回答
1

补充一下 Ben 所说的:您可以使用 的副本解决清空列表问题p,如下所示:

struct dsnode *q = p;
while (q != 0)
{
    printf("%2d ", q->data);
    q = q->next;
}
于 2013-06-04T07:37:04.220 回答