首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

C语言实现的 链表求长度有关问题

2012-07-30 
C语言实现的 链表求长度问题#include stdio.h#include malloc.h#include stdlib.h#define elemtype

C语言实现的 链表求长度问题
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#define elemtype int

struct node
{
elemtype data;
struct node *next;
};

typedef struct node lnode;
typedef struct node *linkedlist;

void linkedlistinit(linkedlist L)
{
L=(lnode *)malloc(sizeof(lnode));
if(L==NULL)
{
printf("申请空间失败!\n");
exit(0);
}
L->next=NULL;
}

int linkedlistlength(linkedlist L)
{
int j=0;
lnode *p;
p=L->next;
while(p!=NULL)
{
printf("here\n");
p=p->next;
j++;
}



return j;
}

void main()
{
int i;
lnode *L;
linkedlistinit(L);
i=linkedlistlength(L);
printf("the length of linkedlist is%d:\n",i);


}


“0X0040d822”指令引用的“0xccccccd0”内存。该内存不能为read  


请教各位大侠 应如何修改啊???????????????????




[解决办法]

C/C++ code
#include <stdio.h>#include <malloc.h>#include <stdlib.h>#define elemtype intstruct node{    elemtype data;    struct node *next;};typedef struct node lnode;typedef struct node *linkedlist;void linkedlistinit(linkedlist *L)//这里参数要用指针的指针里面相应更改{    *L=(lnode *)malloc(sizeof(lnode));    if(*L==NULL)    {        printf("申请空间失败!\n");        exit(0);    }    (*L)->next=NULL;}int linkedlistlength(linkedlist L){    int j=0;    lnode *p;    //p=L->next;    p=L;    //链表第一个元素是L,不是L->next    while(p!=NULL)    {        printf("here\n");        p=p->next;        j++;    }    return j;}void main(){    int i;    lnode *L;    linkedlistinit(&L);    i=linkedlistlength(L);    printf("the length of linkedlist is%d:\n",i);    system("pause");}
[解决办法]
void linkedlistinit(linkedlist *L)
{
(*L)=(lnode *)malloc(sizeof(lnode));
if(L==NULL)
{
printf("申请空间失败!\n");
exit(0);
}
(*L)->next=NULL;
}

int linkedlistlength(linkedlist L)
{
int j=1;
lnode *p;
p=L->next;
while(p!=NULL)
{
printf("here\n");
p=p->next;
j++;
}

return j;
}

void main()
{
int i;
lnode *L = NULL;
linkedlistinit(&L);
i=linkedlistlength(L);
printf("the length of linkedlist is%d:\n",i);
}

好好学习C语言吧,
[解决办法]
main()中lnode *L;没有初始化,应该用lnode *L=NULL;

还有linkedlistlength(linkedlist L)中的p=L->next;需要先判断L->next是否为空,这都是细节问题……
[解决办法]
void linkedlistinit(linkedlist L)
传递的指针没有初始化,它的地址0xccccccd0,传进linkedlistinit函数的时候这个指针强制给赋了一个新的地址0X0040d822,并令其next指针指向0。而在走出这个函数之后,L仍未改变,他的地址依然是0xccccccd0。
可以修改linkedlistinit(linkedlist& L)、linkedlistinit(linkedlist* L)或返回类型linkedlist 


[解决办法]
首先你需要创建一个链表,看到你创建的链表并不完整。先把链表创建好,然后通过遍历来计算出链表的长度即节点的个数。

热点排行