C 链表初始化
我试图用C语言创建一个链表,但列表中比预期多了一个元素C 链表初始化,c,list,C,List,我试图用C语言创建一个链表,但列表中比预期多了一个元素 #define SIZE_OF_LIST 10 int main() { struct node* head = NULL; struct node* item = NULL; int i; head = (struct node*)malloc(sizeof(struct node)); item = (struct node*)malloc(sizeof(struct node) * 10); head
#define SIZE_OF_LIST 10
int main()
{
struct node* head = NULL;
struct node* item = NULL;
int i;
head = (struct node*)malloc(sizeof(struct node));
item = (struct node*)malloc(sizeof(struct node) * 10);
head->data = 999;
head->link = item;
// Create a list of 10 elements
for (i = 0; i < SIZE_OF_LIST; i++)
{
(item+i)->data = i;
printf("(item+%d)->data = %d\n",i,i);
if (i<SIZE_OF_LIST-1)
{
(item+i)->link = (item+i+1);
printf("(item+%d->link = (item+%d+1);\n", i, i);
}
else
{
(item+i)->link = NULL;
printf("(item+%d->link = NULL;\n", i);
}
}
printf("Items : %d\n", getListLength(head));
PrintListData(head);
return 0;
}
所以在列表的第1位似乎有一个额外的元素?我做错了什么?您对
PrintListData
的实现是错误的。应该是:
void PrintListData(struct node* list)
{
int index = 0;
for ( ; list != NULL; list = list->link, ++index )
{
printf("List[%d] = %d\n", index, list->data);
}
}
看看您是如何实现的PrintListData
,我想您在getListLength
getListLength
的实现应该类似于:
int getListLength(struct node* list)
{
int len = 0;
for ( ; list != NULL; list = list->link, ++len );
return len;
}
上述答案正确地指出了问题所在。根据链表的语义,我更愿意实现如下功能:
int getListLength(struct node *head) {
struct node *current = head;
int len = 0;
if (current) {
while(current->link != NULL) {
len ++;
current = current->link;
}
}
return len;
}
void PrintListData(struct node* head) {
int index = 0;
struct node *current = head;
if (current) {
while(current != NULL) {
printf("List[%d] = %d\n", index, current->data);
index ++;
current = current->link;
}
}
}
列表的大小是如何定义的?很抱歉,忘记在代码中包含它了#定义\u列表10的大小\u您的跟踪如何?您是否也可以显示
PrintListData()
的代码?@SSC是的ofc我现在已经把它包括在问题中了。就是这样。谢谢,是的,我的getListLength实现也错了。但是getListLength函数仍然返回10,在我看来应该是11。还是我错了?不,我也不确定我做了什么,现在我的结果是正确的,哈哈。无论如何,非常感谢你的帮助!:]@西科克斯先生,不客气。很高兴你的计划成功了。
int getListLength(struct node* list)
{
int len = 0;
for ( ; list != NULL; list = list->link, ++len );
return len;
}
int getListLength(struct node *head) {
struct node *current = head;
int len = 0;
if (current) {
while(current->link != NULL) {
len ++;
current = current->link;
}
}
return len;
}
void PrintListData(struct node* head) {
int index = 0;
struct node *current = head;
if (current) {
while(current != NULL) {
printf("List[%d] = %d\n", index, current->data);
index ++;
current = current->link;
}
}
}