求助:链表头节点插入数据,调用时又出现不确定的数据
程序代码:// liaobiao11.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "stdio.h"
#include "stdlib.h"
void vprit(struct List_num* vhead);
//==============================================
/*创建链表结构体*/
typedef struct List_num{
int iscrose;
struct List_num* lnext;
}List_num;
//===============================================
/*创建链表*/
int i; //记录节点
struct List_num* lscreate()
{
List_num* lhead, *lnew, *lend;
int inum; //声明一个变量用来录入数据
lhead = (struct List_num*)malloc(sizeof(struct List_num)); //创建头节点
if (lhead == NULL) //如果创建头节点失败,返回NULL
{
printf("头节点创建失败!\n");
return NULL;
}
lhead->lnext = NULL; //头节点指针域初始化为空
lend = lhead; //指针尾部指向头节点
i = 0; //初始化i为0,开始记录节点
lnew = (struct List_num*)malloc(sizeof(struct List_num)); //创建新节点
if (lnew->lnext == NULL) //如果新节点创建失败,返回NULL
{
printf("创建新节点失败!\n");
return NULL;
}
printf("请录入数据:\n");
scanf_s("%d", &inum); //录入数据
while (inum > 0) //如果录入的数据大于0,
{
i++; //节点递增
lnew->iscrose = inum; //新节点保存数据
if (lhead == NULL) //如果头节点为空时,数据保存在头节点
{
lhead = lnew;
}
else
{
lnew->lnext = NULL; //置空新节点下一节点
lend->lnext = lnew; //尾部指针域指向新节点
lend = lnew; //指针尾部抽指新节点
}
lnew = (struct List_num*)malloc(sizeof(struct List_num)); //再次分配新节点
printf("请录入数据:\n");
scanf_s("%d", &inum); //录入数据
}
lnew->lnext = NULL; //置空新节点指针域
return lhead;
}
/*表头插入数据*/
/*n为要插入的数据*/
struct List_num* Linsert(List_num *Lhead, int n)
{
struct List_num* itemp1, *itemp2; //最后调用vprit(itemp2),所以,在之前,itemp2=Lhead.
itemp1 = (struct List_num*)malloc(sizeof(struct List_num)); //创建新节点itemp1
if (itemp1 == NULL) //如果新节点itemp1为NULL时,返回NULL
{
printf("分配新节点失败:\n");
return NULL;
}
else
{
i++; //节点增加
itemp1->iscrose = n; //新节点保存插入的数据
itemp1->lnext = Lhead; //新节点指针域指向头节点
Lhead = itemp1; //指针头节点指向新节点
}
itemp2 = Lhead;
vprit(itemp2); //调用vprit()打印
return Lhead;
}
//================================================================
/*打印链表*/
void vprit(struct List_num* vhead)
{
List_num *p1;
p1 = vhead; //p1保存头节点
if (p1 == NULL) //如果p1为NULL时,提示链表为空
{
printf("链表为空!\n");
}
p1 = p1->lnext; //新节点指针指向下一节点
while (p1!= NULL)
{
printf("节点数为:%d\n", i);
printf("输入的数据为:%d\n",p1->iscrose);
p1 = p1->lnext; //指向下一节点
}
}
/*主函数*/
int _tmain(int argc, _TCHAR* argv[])
{
List_num* itemp;
int n; //用来录入插入的数据
itemp = lscreate(); //创建链表
vprit(itemp); //打印链表
printf("请输入要插入的数据:\n");
scanf_s("%d", &n); //录入要插入的数据
Linsert(itemp, n); //调用Linsert()插入数据
return 0;
}
在调试中,虽然运行成功。但是插入的数据完全是错误的。
调试情况如下:
请录入数据:
11
请录入数据:
12
请录入数据:
13
请录入数据:
14
请录入数据:
0
节点数为:4
输入的数据为:11
节点数为:4
输入的数据为:12
节点数为:4
输入的数据为:13
节点数为:4
输入的数据为:14
请输入要插入的数据:
17
节点数为:5
输入的数据为:-842150451
节点数为:5
输入的数据为:11
节点数为:5
输入的数据为:12
节点数为:5
输入的数据为:13
节点数为:5
输入的数据为:14
请按任意键继续. . .
求助前辈,这要怎么修正。








