cheyuqiao 2016-11-04 15:05 采纳率: 0%
浏览 1392

C语言链表操作第一个数总是0,帮忙看下谢谢

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;

}

  • 写回答

3条回答 默认 最新

  • BlackTangerine 2016-11-04 15:30
    关注

    pHead->next是链表的第一个节点,pHead是表头,数据为0,你输出函数需要改一下

    评论

报告相同问题?

悬赏问题

  • ¥15 我想在一个软件里添加一个优惠弹窗,应该怎么写代码
  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退