持之以恒111 发表于 2013-10-20 19:52:20

C 语言实现单链表,出现错误,

#include <stdio.h>
#include <stdlib.h>
typedef int elemType ;

struct sNode{    /* 定义单链表结点类型 */
        elemType data;
        struct sNode *next;
};
/* 1.初始化线性表,即置单链表的表头指针为空 */
void initList(struct sNode* *hl)
{
        *hl = NULL;
        return;
}

/* 6.遍历一个单链表 */
void traverseList(struct sNode *hl)
{
        while(hl != NULL){
                printf("%5d", hl->data);
                hl = hl->next;
        }
        printf(" ");
        return;
}

/* 10.向单链表的末尾添加一个元素 */
void insertLastList(struct sNode* *hl, elemType x)
{
        struct sNode *newP;
        newP =(sNode *) malloc(sizeof(struct sNode));
        if(newP == NULL){
                printf("内在分配失败,退出运行! ");
                exit(1);
        }
        /* 把x的值赋给新结点的data域,把空值赋给新结点的next域 */
        newP->data = x;
        newP->next = NULL;
        /* 若原表为空,则作为表头结点插入 */
        if(*hl == NULL){
                *hl = newP;      
        }
        /* 查找到表尾结点并完成插入 */
        else{
                struct sNode *p = NULL;
                while(p->next != NULL){
                        p = p->next;
                }
                p->next = newP;
        }
        return;
}

/* 3.返回单链表的长度 */
int sizeList(struct sNode *hl)
{
        int count = 0;      /* 用于统计结点的个数 */
        while(hl != NULL){
                count++;
                hl = hl->next;
        }
        return count;
}

/* 9.向单链表的表头插入一个元素 */
void insertFirstList(struct sNode* *hl, elemType x)
{
        struct sNode *newP;
        newP =(sNode *) malloc(sizeof(struct sNode));
        if(newP == NULL){
                printf("内存分配失败,退出运行! ");
                exit(1);
        }
        newP->data = x;      /* 把x的值赋给新结点的data域 */
        /* 把新结点作为新的表头结点插入 */
        newP->next = *hl;      
        *hl = newP;
        return;
}

int main(int argc, char* argv[])
{
        int a={1,2,3,4,5};
        int i;
        struct sNode *p;
        initList(&p);

        for(i = 0; i < 5; i++){
                insertLastList(&p, a);
        }
        int m=sizeList(p);
        printf("%d\n",m);
        traverseList(p);
}
insertLastList(&p, a);这个函数出现错误,希望大家帮忙修改一下,谢谢了
页: [1]
查看完整版本: C 语言实现单链表,出现错误,