双向链表,尾插函数用了之后得到结果不正常?

typedef struct Dlist //链表结构体
{
Dlist* p_head;
int data;
Dlist* p_last;
}Dlist;

void Initialization(int data, Dlist ** list) //初始化链表
{
Dlist * p = new Dlist;
p->data = data;
p->p_last = NULL;
p->p_head = NULL;
*list = p;
}

void InsertNode_head(int data, Dlist ** list) //头部插入
{
while ((*list)->p_last != NULL)
{
(*list)->p_last = (*list)->p_last->p_last;
}
Dlist * p = new Dlist;
p->data = data;
p->p_last = NULL;
p->p_head =*list;
(*list)->p_last = p;
*list = p;
}

void InsertNode_end(int data,Dlist**list) //尾部插入
{
while ((*list)->p_head != NULL)
{
(*list)->p_head = (*list)->p_head->p_head;
}
if ((*list)->p_head = NULL)
{
printf("我是空");
}

Dlist * p = new Dlist;
p->data = data;
p->p_last = *list;
p->p_head = NULL;
(*list)->p_head = p;

}void print(Dlist * list) //打印数据
{
while (list->p_last!=NULL)
{
list->p_last = list->p_last->p_last;
}
while (list->p_head!= NULL)
{
printf("%d\n", list->data);

    list  = list->p_head;
}
printf("最后一个数是:");
printf("%d", list->data);

}
//函数原型 void InsertNode(int data, Dlist * list); 其中data是需要插入的数据,list是链表的结构体指针
//链表的结构体中有如下内容 typedef struct Dlist { Node* p_head; Node* p_last; }Dlist;
int main()
{
Dlist* list = new Dlist;
Initialization(1, &list);
InsertNode_head(2, &list);
InsertNode_head(4, &list);

InsertNode_end(4, &list);

print(list);
getchar();

}

结果显示:
4
最后一个数:4

如果不用尾插函数一切正常,如果用了,显示结果就不正常,求大神解答
weixin_44826062
moon19961996 说错了,我删除了吧
8 个月之前 回复

1个回答

首先,P_Last这个名字我给你换了,因为它会误导人,双链表的前驱节点指针应该叫Prev(ious),而Last这个单词表示最后的意思,

#include <iostream>
using namespace std;

typedef struct Dlist 
{
    Dlist* p_Prev;
    int data;
    Dlist* p_Next;
}Dlist;

void Initialization(int data, Dlist ** list)
{
    Dlist * p = new Dlist; 
    p->data = data;

    p->p_Next = NULL;
    p->p_Prev = NULL;
    *list = p;
}

void InsertNode_head(int data, Dlist ** list)
{
    Dlist * p = new Dlist; 
    p->data = data;
    p->p_Next = *list;
    p->p_Prev = NULL;
    *list = p;
}
void InsertNode_end(int data,Dlist*list)
{
    while (list->p_Next != NULL)   
    {
        list = list->p_Next;
    }

    Dlist * p = new Dlist; 
    p->data = data;        
    p->p_Next = NULL;      
    p->p_Prev = list;  
    list->p_Next = p;
}

void print(Dlist*list)
{
    while (list != NULL)   
    {
        cout << list->data << " ";
        list = list->p_Next;
    }
}

int main()
{
    Dlist* list = new Dlist;
    Initialization(1, &list);
    InsertNode_head(2, &list);
    InsertNode_head(4, &list);
    InsertNode_end(4, list);
    print(list);
    getchar();
}

4 2 1 4

weixin_44826062
moon19961996 貌似是我强行用了二级指针,把二级指针改为一级指针就好了,可是我不明白,头插用二级就可以,为什么尾插用二级就炸了
8 个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!