C语言写单链表,插入数据的时候第一个数不管输入的是多少都是0。大家帮忙看下哪里错了呀?谢谢了。
//结点结构定义
struct node
{
int data;
struct node *next;
};
//单链表的基本结构体
typedef struct list
{
struct node pHead;
int length;
}LinkList;
/***************功能1:创建一个单向链表****************/
int createList(struct node **pHead){
struct node *pNew;
if (pHead == NULL) //参数校验
{
return PARAM_ERROR;
}
//创建表头结点
pNew = (struct node *)malloc(sizeof(struct node));//申请空间
if (pNew==NULL)
{
return MALLOC_ERROR;
}
memset(pNew, 0, sizeof(struct node));
pNew->data = 0;
pNew->next = NULL;//空表,没有后续结点
*pHead = pNew;
return 0;
}
/**********功能4:插入结点***********/
int Insert(struct node *pHead, int value, int pos)
{
int icount = 0; //计数器
struct node *p;
struct node *pNew = NULL;
//struct node *pPre = NULL;
//参数校验
if (pHead==NULL)
{
return PARAM_ERROR;
}
p = pHead;
//寻找第pos-1个结点,令p指向它
while( p!=NULL && icount < pos-1)
{
//printf("%d ", icount);
p=p->next;
icount++;
}
//申请新结点pNew
pNew = (struct node *)malloc(sizeof(struct node));
if (pNew==NULL)
{
return MALLOC_ERROR;
}
pNew->data =value;
pNew->next = p->next ; //在p结点之后插入新结点
p->next = pNew;
return 0;
}
//主函数
int main(void)
{
int ret;
struct node *pHead;
//创建链表,并填入数据
ret= createList(&pHead);
//printf("%d",ret); //创建成功
//插入数据
ret = Insert(pHead, 3, 0);
ret = Insert(pHead, 8, 1);
ret = Insert(pHead, 1, 2);
ret = Insert(pHead, 7, 3);
//printf("%d",ret);//插入成功
//输出
ret = output(pHead);
//根据角标查找数据
ret = Get(pHead, 2 , 0);
printf("get at 2 is %d\n", ret);
//查询表长
ret = ListLength(pHead);
printf("list length is %d\n", ret);
//删除数据
ret = Delete(pHead, 1 ,0);
printf("already del num %d\n",ret);
ret = ListLength(pHead);
printf("list length is %d\n", ret);
ret = output(pHead);
//销毁链表
ret = destroyList(pHead);
if (ret == 0)
{
printf("销毁成功!\n");
}
else
{
printf("销毁失败!\n");
ret = ListLength(pHead);
printf("list length is %d\n", ret);
}
return 0;
}