weixin_44826062
moon19961996
2019-04-05 20:58

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

5
  • c++
  • c语言

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

如果不用尾插函数一切正常,如果用了,显示结果就不正常,求大神解答
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答