看看这个链表程序
想实现数据结构中的一个程序
程序结果是返回链表长度
#include <iostream.h>
#include <stdio.h>
#include <malloc.h>
#define MAXSIZE 100
struct LNode
{
char date;
LNode *next;
};
int ListLength(LNode *L);
int main()
{
int Length,i=0;
char string[] = { "The ListLength Programme "};
LNode *LinkList,*Lnode;
LinkList = (LNode *) malloc (sizeof(LNode));
Lnode = (LNode *)malloc (sizeof(LNode));
if(!LinkList||!Lnode)
{
cout < < "malloc space error! " < <endl;
return 0;
}
Lnode = LinkList;
while(string[i])
{
LinkList-> date = string[i++];
LinkList = LinkList-> next;
}
LinkList-> next = NULL;
Length = ListLength(Lnode);
cout < < "The String Length is " < <Length < <endl;
return 0;
}
int ListLength(LNode *L)
{
int Length = 0;
LNode *p;
p = (LNode *) malloc (sizeof(LNode));
p = L;
while(p!=NULL)
{
Length++;
p = p-> next;
}
return Length;
}
运行时LinkList指针指向了不当的位置导致错误
请问错在哪?
[解决办法]
你只malloc了一个地址,而且也没有对next赋值。链表的长度是1。当然要出错了